Skip to contentSkip to conversation

bitbake/bs4: Upgrade 4.3.2 -> 4.4.1 (python 3 version)

PATCH In review Richard Purdie 1 participant 29 messages Jun 1, 2016 Library code

lore
Share & tools
lore
#0 lore raw

PATCH 1/28 bitbake/bs4: Upgrade 4.3.2 -> 4.4.1 (python 3 version)

Upgrade to 4.4.1 which has been run through 2to3 as per the maintainers recommendation for v3 use.

---
 lib/bs4/__init__.py                    | 112 ++++++++---
 lib/bs4/builder/__init__.py            |   7 +-
 lib/bs4/builder/_html5lib.py           |  71 +++++--
 lib/bs4/builder/_htmlparser.py         |  56 +++---
 lib/bs4/builder/_lxml.py               |  47 +++--
 lib/bs4/dammit.py                      |  31 ++-
 lib/bs4/diagnose.py                    |  68 ++++---
 lib/bs4/element.py                     | 346 ++++++++++++++++++++++-----------
 lib/bs4/testing.py                     | 129 ++++++++++--
 lib/bs4/tests/test_builder_registry.py |  14 +-
 lib/bs4/tests/test_html5lib.py         |  19 +-
 lib/bs4/tests/test_htmlparser.py       |  13 ++
 lib/bs4/tests/test_lxml.py             |  19 +-
 lib/bs4/tests/test_soup.py             | 107 +++++++---
 lib/bs4/tests/test_tree.py             | 294 ++++++++++++++++++++++------
 15 files changed, 972 insertions(+), 361 deletions(-)
lib/bs4/__init__.py +87 -25
index 7ba3426..f6fdfd5 100644
@@ -17,8 +17,8 @@ http://www.crummy.com/software/BeautifulSoup/bs4/doc/
 """
 
 __author__ = "Leonard Richardson ([email protected])"
-__version__ = "4.3.2"
-__copyright__ = "Copyright (c) 2004-2013 Leonard Richardson"
+__version__ = "4.4.1"
+__copyright__ = "Copyright (c) 2004-2015 Leonard Richardson"
 __license__ = "MIT"
 
 __all__ = ['BeautifulSoup']
@@ -45,7 +45,7 @@ from .element import (
 
 # The very first thing we do is give a useful error if someone is
 # running this code under Python 3 without converting it.
-syntax_error = u'You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work. You need to convert the code, either by installing it (`python setup.py install`) or by running 2to3 (`2to3 -w bs4`).'
+'You are trying to run the Python 2 version of Beautiful Soup under Python 3. This will not work.'!='You need to convert the code, either by installing it (`python setup.py install`) or by running 2to3 (`2to3 -w bs4`).'
 
 class BeautifulSoup(Tag):
     """
@@ -69,7 +69,7 @@ class BeautifulSoup(Tag):
     like HTML's <br> tag), call handle_starttag and then
     handle_endtag.
     """
-    ROOT_TAG_NAME = u'[document]'
+    ROOT_TAG_NAME = '[document]'
 
     # If the end-user gives no indication which tree builder they
     # want, look for one with these features.
@@ -77,8 +77,11 @@ class BeautifulSoup(Tag):
 
     ASCII_SPACES = '\x20\x0a\x09\x0c\x0d'
 
+    NO_PARSER_SPECIFIED_WARNING = "No parser was explicitly specified, so I'm using the best available %(markup_type)s parser for this system (\"%(parser)s\"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.\n\nTo get rid of this warning, change this:\n\n BeautifulSoup([your markup])\n\nto this:\n\n BeautifulSoup([your markup], \"%(parser)s\")\n"
+
     def __init__(self, markup="", features=None, builder=None,
-                 parse_only=None, from_encoding=None, **kwargs):
+                 parse_only=None, from_encoding=None, exclude_encodings=None,
+                 **kwargs):
         """The Soup object is initialized as the 'root tag', and the
         provided markup (which can be a string or a file-like object)
         is fed into the underlying parser."""
@@ -114,9 +117,9 @@ class BeautifulSoup(Tag):
             del kwargs['isHTML']
             warnings.warn(
                 "BS4 does not respect the isHTML argument to the "
-                "BeautifulSoup constructor. You can pass in features='html' "
-                "or features='xml' to get a builder capable of handling "
-                "one or the other.")
+                "BeautifulSoup constructor. Suggest you use "
+                "features='lxml' for HTML and features='lxml-xml' for "
+                "XML.")
 
         def deprecated_argument(old_name, new_name):
             if old_name in kwargs:
@@ -135,12 +138,13 @@ class BeautifulSoup(Tag):
             "fromEncoding", "from_encoding")
 
         if len(kwargs) > 0:
-            arg = kwargs.keys().pop()
+            arg = list(kwargs.keys()).pop()
             raise TypeError(
                 "__init__() got an unexpected keyword argument '%s'" % arg)
 
         if builder is None:
-            if isinstance(features, basestring):
+            original_features = features
+            if isinstance(features, str):
                 features = [features]
             if features is None or len(features) == 0:
                 features = self.DEFAULT_BUILDER_FEATURES
@@ -151,6 +155,16 @@ class BeautifulSoup(Tag):
                     "requested: %s. Do you need to install a parser library?"
                     % ",".join(features))
             builder = builder_class()
+            if not (original_features == builder.NAME or
+                    original_features in builder.ALTERNATE_NAMES):
+                if builder.is_xml:
+                    markup_type = "XML"
+                else:
+                    markup_type = "HTML"
+                warnings.warn(self.NO_PARSER_SPECIFIED_WARNING % dict(
+                    parser=builder.NAME,
+                    markup_type=markup_type))
+
         self.builder = builder
         self.is_xml = builder.is_xml
         self.builder.soup = self
@@ -164,7 +178,7 @@ class BeautifulSoup(Tag):
             # involving passing non-markup to Beautiful Soup.
             # Beautiful Soup will still parse the input as markup,
             # just in case that's what the user really wants.
-            if (isinstance(markup, unicode)
+            if (isinstance(markup, str)
                 and not os.path.supports_unicode_filenames):
                 possible_filename = markup.encode("utf8")
             else:
@@ -172,25 +186,30 @@ class BeautifulSoup(Tag):
             is_file = False
             try:
                 is_file = os.path.exists(possible_filename)
-            except Exception, e:
+            except Exception as e:
                 # This is almost certainly a problem involving
                 # characters not valid in filenames on this
                 # system. Just let it go.
                 pass
             if is_file:
+                if isinstance(markup, str):
+                    markup = markup.encode("utf8")
                 warnings.warn(
                     '"%s" looks like a filename, not markup. You should probably open this file and pass the filehandle into Beautiful Soup.' % markup)
             if markup[:5] == "http:" or markup[:6] == "https:":
                 # TODO: This is ugly but I couldn't get it to work in
                 # Python 3 otherwise.
                 if ((isinstance(markup, bytes) and not b' ' in markup)
-                    or (isinstance(markup, unicode) and not u' ' in markup)):
+                    or (isinstance(markup, str) and not ' ' in markup)):
+                    if isinstance(markup, str):
+                        markup = markup.encode("utf8")
                     warnings.warn(
                         '"%s" looks like a URL. Beautiful Soup is not an HTTP client. You should probably use an HTTP client to get the document behind the URL, and feed that document to Beautiful Soup.' % markup)
 
         for (self.markup, self.original_encoding, self.declared_html_encoding,
          self.contains_replacement_characters) in (
-            self.builder.prepare_markup(markup, from_encoding)):
+             self.builder.prepare_markup(
+                 markup, from_encoding, exclude_encodings=exclude_encodings)):
             self.reset()
             try:
                 self._feed()
@@ -203,6 +222,16 @@ class BeautifulSoup(Tag):
         self.markup = None
         self.builder.soup = None
 
+    def __copy__(self):
+        return type(self)(self.encode(), builder=self.builder)
+
+    def __getstate__(self):
+        # Frequently a tree builder can't be pickled.
+        d = dict(self.__dict__)
+        if 'builder' in d and not self.builder.picklable:
+            del d['builder']
+        return d
+
     def _feed(self):
         # Convert the document to Unicode.
         self.builder.reset()
@@ -229,9 +258,7 @@ class BeautifulSoup(Tag):
 
     def new_string(self, s, subclass=NavigableString):
         """Create a new NavigableString associated with this soup."""
-        navigable = subclass(s)
-        navigable.setup()
-        return navigable
+        return subclass(s)
 
     def insert_before(self, successor):
         raise NotImplementedError("BeautifulSoup objects don't support insert_before().")
@@ -259,7 +286,7 @@ class BeautifulSoup(Tag):
 
     def endData(self, containerClass=NavigableString):
         if self.current_data:
-            current_data = u''.join(self.current_data)
+            current_data = ''.join(self.current_data)
             # If whitespace is not preserved, and this string contains
             # nothing but ASCII spaces, replace it with a single space
             # or newline.
@@ -290,14 +317,49 @@ class BeautifulSoup(Tag):
     def object_was_parsed(self, o, parent=None, most_recent_element=None):
         """Add an object to the parse tree."""
         parent = parent or self.currentTag
-        most_recent_element = most_recent_element or self._most_recent_element
-        o.setup(parent, most_recent_element)
+        previous_element = most_recent_element or self._most_recent_element
+
+        next_element = previous_sibling = next_sibling = None
+        if isinstance(o, Tag):
+            next_element = o.next_element
+            next_sibling = o.next_sibling
+            previous_sibling = o.previous_sibling
+            if not previous_element:
+                previous_element = o.previous_element
+
+        o.setup(parent, previous_element, next_element, previous_sibling, next_sibling)
 
-        if most_recent_element is not None:
-            most_recent_element.next_element = o
         self._most_recent_element = o
         parent.contents.append(o)
 
+        if parent.next_sibling:
+            # This node is being inserted into an element that has
+            # already been parsed. Deal with any dangling references.
+            index = parent.contents.index(o)
+            if index == 0:
+                previous_element = parent
+                previous_sibling = None
+            else:
+                previous_element = previous_sibling = parent.contents[index-1]
+            if index == len(parent.contents)-1:
+                next_element = parent.next_sibling
+                next_sibling = None
+            else:
+                next_element = next_sibling = parent.contents[index+1]
+
+            o.previous_element = previous_element
+            if previous_element:
+                previous_element.next_element = o
+            o.next_element = next_element
+            if next_element:
+                next_element.previous_element = o
+            o.next_sibling = next_sibling
+            if next_sibling:
+                next_sibling.previous_sibling = o
+            o.previous_sibling = previous_sibling
+            if previous_sibling:
+                previous_sibling.next_sibling = o
+
     def _popToTag(self, name, nsprefix=None, inclusivePop=True):
         """Pops the tag stack up to and including the most recent
         instance of the given tag. If inclusivePop is false, pops the tag
@@ -367,9 +429,9 @@ class BeautifulSoup(Tag):
             encoding_part = ''
             if eventual_encoding != None:
                 encoding_part = ' encoding="%s"' % eventual_encoding
-            prefix = u'<?xml version="1.0"%s?>\n' % encoding_part
+            prefix = '<?xml version="1.0"%s?>\n' % encoding_part
         else:
-            prefix = u''
+            prefix = ''
         if not pretty_print:
             indent_level = None
         else:
@@ -403,4 +465,4 @@ class FeatureNotFound(ValueError):
 if __name__ == '__main__':
     import sys
     soup = BeautifulSoup(sys.stdin)
-    print soup.prettify()
+    print(soup.prettify())
lib/bs4/builder/__init__.py +5 -2
index 740f5f2..6ccd4d2 100644
@@ -80,9 +80,12 @@ builder_registry = TreeBuilderRegistry()
 class TreeBuilder(object):
     """Turn a document into a Beautiful Soup object tree."""
 
+    NAME = "[Unknown tree builder]"
+    ALTERNATE_NAMES = []
     features = []
 
     is_xml = False
+    picklable = False
     preserve_whitespace_tags = set()
     empty_element_tags = None # A tag will be considered an empty-element
                               # tag when and only when it has no contents.
@@ -153,13 +156,13 @@ class TreeBuilder(object):
             universal = self.cdata_list_attributes.get('*', [])
             tag_specific = self.cdata_list_attributes.get(
                 tag_name.lower(), None)
-            for attr in attrs.keys():
+            for attr in list(attrs.keys()):
                 if attr in universal or (tag_specific and attr in tag_specific):
                     # We have a "class"-type attribute whose string
                     # value is a whitespace-separated list of
                     # values. Split it into a list.
                     value = attrs[attr]
-                    if isinstance(value, basestring):
+                    if isinstance(value, str):
                         values = whitespace_re.split(value)
                     else:
                         # html5lib sometimes calls setAttributes twice
lib/bs4/builder/_html5lib.py +59 -12

173 lines not on this page · raw message

lib/bs4/builder/_htmlparser.py +30 -26

113 lines not on this page · raw message

lib/bs4/builder/_lxml.py +31 -16

136 lines not on this page · raw message

lib/bs4/dammit.py +21 -10
index 59640b7..68d419f 100644
@@ -3,12 +3,14 @@
 
 This library converts a bytestream to Unicode through any means
 necessary. It is heavily based on code from Mark Pilgrim's Universal
-Feed Parser. It works best on XML and XML, but it does not rewrite the
+Feed Parser. It works best on XML and HTML, but it does not rewrite the
 XML or HTML to reflect a new encoding; that's the tree builder's job.
 """
+__license__ = "MIT"
 
+from pdb import set_trace
 import codecs
-from htmlentitydefs import codepoint2name
+from html.entities import codepoint2name
 import re
 import logging
 import string
@@ -56,7 +58,7 @@ class EntitySubstitution(object):
         reverse_lookup = {}
         characters_for_re = []
         for codepoint, name in list(codepoint2name.items()):
-            character = unichr(codepoint)
+            character = chr(codepoint)
             if codepoint != 34:
                 # There's no point in turning the quotation mark into
                 # &quot;, unless it happens within an attribute value, which
@@ -212,8 +214,11 @@ class EncodingDetector:
 
     5. Windows-1252.
     """
-    def __init__(self, markup, override_encodings=None, is_html=False):
+    def __init__(self, markup, override_encodings=None, is_html=False,
+                 exclude_encodings=None):
         self.override_encodings = override_encodings or []
+        exclude_encodings = exclude_encodings or []
+        self.exclude_encodings = set([x.lower() for x in exclude_encodings])
         self.chardet_encoding = None
         self.is_html = is_html
         self.declared_encoding = None
@@ -224,6 +229,8 @@ class EncodingDetector:
     def _usable(self, encoding, tried):
         if encoding is not None:
             encoding = encoding.lower()
+            if encoding in self.exclude_encodings:
+                return False
             if encoding not in tried:
                 tried.add(encoding)
                 return True
@@ -266,6 +273,9 @@ class EncodingDetector:
     def strip_byte_order_mark(cls, data):
         """If a byte-order mark is present, strip it and return the encoding it implies."""
         encoding = None
+        if isinstance(data, str):
+            # Unicode data cannot have a byte-order mark.
+            return data, encoding
         if (len(data) >= 4) and (data[:2] == b'\xfe\xff') \
                and (data[2:4] != '\x00\x00'):
             encoding = 'utf-16be'
@@ -306,7 +316,7 @@ class EncodingDetector:
             declared_encoding_match = html_meta_re.search(markup, endpos=html_endpos)
         if declared_encoding_match is not None:
             declared_encoding = declared_encoding_match.groups()[0].decode(
-                'ascii')
+                'ascii', 'replace')
         if declared_encoding:
             return declared_encoding.lower()
         return None
@@ -331,18 +341,19 @@ class UnicodeDammit:
         ]
 
     def __init__(self, markup, override_encodings=[],
-                 smart_quotes_to=None, is_html=False):
+                 smart_quotes_to=None, is_html=False, exclude_encodings=[]):
         self.smart_quotes_to = smart_quotes_to
         self.tried_encodings = []
         self.contains_replacement_characters = False
         self.is_html = is_html
 
-        self.detector = EncodingDetector(markup, override_encodings, is_html)
+        self.detector = EncodingDetector(
+            markup, override_encodings, is_html, exclude_encodings)
 
         # Short-circuit if the data is in Unicode to begin with.
-        if isinstance(markup, unicode) or markup == '':
+        if isinstance(markup, str) or markup == '':
             self.markup = markup
-            self.unicode_markup = unicode(markup)
+            self.unicode_markup = str(markup)
             self.original_encoding = None
             return
 
@@ -425,7 +436,7 @@ class UnicodeDammit:
     def _to_unicode(self, data, encoding, errors="strict"):
         '''Given a string and its encoding, decodes the string into Unicode.
         %encoding is a string recognized by encodings.aliases'''
-        return unicode(data, encoding, errors)
+        return str(data, encoding, errors)
 
     @property
     def declared_html_encoding(self):
lib/bs4/diagnose.py +40 -28

139 lines not on this page · raw message

lib/bs4/element.py +230 -116

691 lines not on this page · raw message

lib/bs4/testing.py +112 -17

260 lines not on this page · raw message

lib/bs4/tests/test_builder_registry.py +10 -4
index 92ad10f..90cad82 100644
@@ -1,6 +1,7 @@
 """Tests of the builder registry."""
 
 import unittest
+import warnings
 
 from bs4 import BeautifulSoup
 from bs4.builder import (
@@ -67,10 +68,15 @@ class BuiltInRegistryTest(unittest.TestCase):
                           HTMLParserTreeBuilder)
 
     def test_beautifulsoup_constructor_does_lookup(self):
-        # You can pass in a string.
-        BeautifulSoup("", features="html")
-        # Or a list of strings.
-        BeautifulSoup("", features=["html", "fast"])
+
+        with warnings.catch_warnings(record=True) as w:
+            # This will create a warning about not explicitly
+            # specifying a parser, but we'll ignore it.
+
+            # You can pass in a string.
+            BeautifulSoup("", features="html")
+            # Or a list of strings.
+            BeautifulSoup("", features=["html", "fast"])
 
         # You'll get an exception if BS can't find an appropriate
         # builder.
lib/bs4/tests/test_html5lib.py +16 -3
index 594c3e1..a7494ca 100644
@@ -5,7 +5,7 @@ import warnings
 try:
     from bs4.builder import HTML5TreeBuilder
     HTML5LIB_PRESENT = True
-except ImportError, e:
+except ImportError as e:
     HTML5LIB_PRESENT = False
 from bs4.element import SoupStrainer
 from bs4.testing import (
@@ -74,12 +74,25 @@ class HTML5LibBuilderSmokeTest(SoupTest, HTML5TreeBuilderSmokeTest):
     def test_reparented_markup(self):
         markup = '<p><em>foo</p>\n<p>bar<a></a></em></p>'
         soup = self.soup(markup)
-        self.assertEqual(u"<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p></body>", soup.body.decode())
+        self.assertEqual("<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p></body>", soup.body.decode())
         self.assertEqual(2, len(soup.find_all('p')))
 
 
     def test_reparented_markup_ends_with_whitespace(self):
         markup = '<p><em>foo</p>\n<p>bar<a></a></em></p>\n'
         soup = self.soup(markup)
-        self.assertEqual(u"<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p>\n</body>", soup.body.decode())
+        self.assertEqual("<body><p><em>foo</em></p><em>\n</em><p><em>bar<a></a></em></p>\n</body>", soup.body.decode())
         self.assertEqual(2, len(soup.find_all('p')))
+
+    def test_processing_instruction(self):
+        """Processing instructions become comments."""
+        markup = b"""<?PITarget PIContent?>"""
+        soup = self.soup(markup)
+        assert str(soup).startswith("<!--?PITarget PIContent?-->")
+
+    def test_cloned_multivalue_node(self):
+        markup = b"""<a class="my_class"><p></a>"""
+        soup = self.soup(markup)
+        a1, a2 = soup.find_all('a')
+        self.assertEqual(a1, a2)
+        assert a1 is not a2
lib/bs4/tests/test_htmlparser.py +13 -0
index bcb5ed2..b45e35f 100644
@@ -1,6 +1,8 @@
 """Tests to ensure that the html.parser tree builder generates good
 trees."""
 
+from pdb import set_trace
+import pickle
 from bs4.testing import SoupTest, HTMLTreeBuilderSmokeTest
 from bs4.builder import HTMLParserTreeBuilder
 
@@ -17,3 +19,14 @@ class HTMLParserTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
     def test_namespaced_public_doctype(self):
         # html.parser can't handle namespaced doctypes, so skip this one.
         pass
+
+    def test_builder_is_pickled(self):
+        """Unlike most tree builders, HTMLParserTreeBuilder and will
+        be restored after pickling.
+        """
+        tree = self.soup("<a><b>foo</a>")
+        dumped = pickle.dumps(tree, 2)
+        loaded = pickle.loads(dumped)
+        self.assertTrue(isinstance(loaded.builder, type(tree.builder)))
+
+
lib/bs4/tests/test_lxml.py +2 -17
index 2b2e9b7..6c2a1d7 100644
@@ -7,7 +7,7 @@ try:
     import lxml.etree
     LXML_PRESENT = True
     LXML_VERSION = lxml.etree.LXML_VERSION
-except ImportError, e:
+except ImportError as e:
     LXML_PRESENT = False
     LXML_VERSION = (0,)
 
@@ -62,24 +62,9 @@ class LXMLTreeBuilderSmokeTest(SoupTest, HTMLTreeBuilderSmokeTest):
         # if one is installed.
         with warnings.catch_warnings(record=True) as w:
             soup = BeautifulStoneSoup("<b />")
-        self.assertEqual(u"<b/>", unicode(soup.b))
+        self.assertEqual("<b/>", str(soup.b))
         self.assertTrue("BeautifulStoneSoup class is deprecated" in str(w[0].message))
 
-    def test_real_xhtml_document(self):
-        """lxml strips the XML definition from an XHTML doc, which is fine."""
-        markup = b"""<?xml version="1.0" encoding="utf-8"?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head><title>Hello.</title></head>
-<body>Goodbye.</body>
-</html>"""
-        soup = self.soup(markup)
-        self.assertEqual(
-            soup.encode("utf-8").replace(b"\n", b''),
-            markup.replace(b'\n', b'').replace(
-                b'<?xml version="1.0" encoding="utf-8"?>', b''))
-
-
 @skipIf(
     not LXML_PRESENT,
     "lxml seems not to be present, not testing its XML tree builder.")
lib/bs4/tests/test_soup.py +78 -29

244 lines not on this page · raw message

lib/bs4/tests/test_tree.py +238 -56

594 lines not on this page · raw message

Signature · 1 line
2.5.0
#1 lore raw

PATCH 2/28 bitbake/pyinotify.py: Upgrade to py3 version

---
 lib/pyinotify.py | 256 ++++++++++++++++++++++---------------------------------
 1 file changed, 101 insertions(+), 155 deletions(-)
lib/pyinotify.py +101 -155
index 2dae002..4eb03b0 100644
@@ -42,13 +42,14 @@ class UnsupportedPythonVersionError(PyinotifyError):
         @param version: Current Python version
         @type version: string
         """
-        err = 'Python %s is unsupported, requires at least Python 2.4'
-        PyinotifyError.__init__(self, err % version)
+        PyinotifyError.__init__(self,
+                                ('Python %s is unsupported, requires '
+                                 'at least Python 3.0') % version)
 
 
 # Check Python version
 import sys
-if sys.version_info < (2, 4):
+if sys.version_info < (3, 0):
     raise UnsupportedPythonVersionError(sys.version)
 
 
@@ -68,6 +69,8 @@ from datetime import datetime, timedelta
 import time
 import re
 import asyncore
+import glob
+import locale
 import subprocess
 
 try:
@@ -76,12 +79,6 @@ except ImportError:
     pass  # Will fail on Python 2.4 which has reduce() builtin anyway.
 
 try:
-    from glob import iglob as glob
-except ImportError:
-    # Python 2.4 does not have glob.iglob().
-    from glob import glob as glob
-
-try:
     import ctypes
     import ctypes.util
 except ImportError:
@@ -95,9 +92,7 @@ except ImportError:
 
 __author__ = "[email protected] (Sebastien Martini)"
 
-__version__ = "0.9.5"
-
-__metaclass__ = type  # Use new-style classes by default
+__version__ = "0.9.6"
 
 
 # Compatibity mode: set to True to improve compatibility with
@@ -122,6 +117,9 @@ class INotifyWrapper:
     """
     @staticmethod
     def create():
+        """
+        Factory method instanciating and returning the right wrapper.
+        """
         # First, try to use ctypes.
         if ctypes:
             inotify = _CtypesLibcINotifyWrapper()
@@ -173,7 +171,7 @@ class _INotifySyscallsWrapper(INotifyWrapper):
     def _inotify_init(self):
         try:
             fd = inotify_syscalls.inotify_init()
-        except IOError, err:
+        except IOError as err:
             self._last_errno = err.errno
             return -1
         return fd
@@ -181,7 +179,7 @@ class _INotifySyscallsWrapper(INotifyWrapper):
     def _inotify_add_watch(self, fd, pathname, mask):
         try:
             wd = inotify_syscalls.inotify_add_watch(fd, pathname, mask)
-        except IOError, err:
+        except IOError as err:
             self._last_errno = err.errno
             return -1
         return wd
@@ -189,7 +187,7 @@ class _INotifySyscallsWrapper(INotifyWrapper):
     def _inotify_rm_watch(self, fd, wd):
         try:
             ret = inotify_syscalls.inotify_rm_watch(fd, wd)
-        except IOError, err:
+        except IOError as err:
             self._last_errno = err.errno
             return -1
         return ret
@@ -213,17 +211,8 @@ class _CtypesLibcINotifyWrapper(INotifyWrapper):
         except (OSError, IOError):
             pass  # Will attemp to load it with None anyway.
 
-        if sys.version_info >= (2, 6):
-            self._libc = ctypes.CDLL(libc_name, use_errno=True)
-            self._get_errno_func = ctypes.get_errno
-        else:
-            self._libc = ctypes.CDLL(libc_name)
-            try:
-                location = self._libc.__errno_location
-                location.restype = ctypes.POINTER(ctypes.c_int)
-                self._get_errno_func = lambda: location().contents.value
-            except AttributeError:
-                pass
+        self._libc = ctypes.CDLL(libc_name, use_errno=True)
+        self._get_errno_func = ctypes.get_errno
 
         # Eventually check that libc has needed inotify bindings.
         if (not hasattr(self._libc, 'inotify_init') or
@@ -241,9 +230,8 @@ class _CtypesLibcINotifyWrapper(INotifyWrapper):
         return True
 
     def _get_errno(self):
-        if self._get_errno_func is not None:
-            return self._get_errno_func()
-        return None
+        assert self._get_errno_func
+        return self._get_errno_func()
 
     def _inotify_init(self):
         assert self._libc is not None
@@ -251,6 +239,11 @@ class _CtypesLibcINotifyWrapper(INotifyWrapper):
 
     def _inotify_add_watch(self, fd, pathname, mask):
         assert self._libc is not None
+        # Encodes path to a bytes string. This conversion seems required because
+        # ctypes.create_string_buffer seems to manipulate bytes internally.
+        # Moreover it seems that inotify_add_watch does not work very well when
+        # it receives an ctypes.create_unicode_buffer instance as argument.
+        pathname = pathname.encode(sys.getfilesystemencoding())
         pathname = ctypes.create_string_buffer(pathname)
         return self._libc.inotify_add_watch(fd, pathname, mask)
 
@@ -258,10 +251,6 @@ class _CtypesLibcINotifyWrapper(INotifyWrapper):
         assert self._libc is not None
         return self._libc.inotify_rm_watch(fd, wd)
 
-    def _sysctl(self, *args):
-        assert self._libc is not None
-        return self._libc.sysctl(*args)
-
 
 # Logging
 def logger_init():
@@ -278,97 +267,58 @@ log = logger_init()
 
 
 # inotify's variables
-class SysCtlINotify:
+class ProcINotify:
     """
-    Access (read, write) inotify's variables through sysctl. Usually it
-    requires administrator rights to update them.
+    Access (read, write) inotify's variables through /proc/sys/. Note that
+    usually it requires administrator rights to update them.
 
     Examples:
       - Read max_queued_events attribute: myvar = max_queued_events.value
       - Update max_queued_events attribute: max_queued_events.value = 42
     """
-
-    inotify_attrs = {'max_user_instances': 1,
-                     'max_user_watches': 2,
-                     'max_queued_events': 3}
-
-    def __init__(self, attrname, inotify_wrapper):
-        # FIXME: right now only supporting ctypes
-        assert ctypes
-        self._attrname = attrname
-        self._inotify_wrapper = inotify_wrapper
-        sino = ctypes.c_int * 3
-        self._attr = sino(5, 20, SysCtlINotify.inotify_attrs[attrname])
-
-    @staticmethod
-    def create(attrname):
-        """
-        Factory method instanciating and returning the right wrapper.
-        """
-        # FIXME: right now only supporting ctypes
-        if ctypes is None:
-            return None
-        inotify_wrapper = _CtypesLibcINotifyWrapper()
-        if not inotify_wrapper.init():
-            return None
-        return SysCtlINotify(attrname, inotify_wrapper)
+    def __init__(self, attr):
+        self._base = "/proc/sys/fs/inotify"
+        self._attr = attr
 
     def get_val(self):
         """
-        Gets attribute's value. Raises OSError if the operation failed.
+        Gets attribute's value.
 
         @return: stored value.
         @rtype: int
+        @raise IOError: if corresponding file in /proc/sys cannot be read.
         """
-        oldv = ctypes.c_int(0)
-        size = ctypes.c_int(ctypes.sizeof(oldv))
-        sysctl = self._inotify_wrapper._sysctl
-        res = sysctl(self._attr, 3,
-                     ctypes.c_voidp(ctypes.addressof(oldv)),
-                     ctypes.addressof(size),
-                     None, 0)
-        if res == -1:
-            raise OSError(self._inotify_wrapper.get_errno(),
-                          self._inotify_wrapper.str_errno())
-        return oldv.value
+        with open(os.path.join(self._base, self._attr), 'r') as file_obj:
+            return int(file_obj.readline())
 
     def set_val(self, nval):
         """
-        Sets new attribute's value. Raises OSError if the operation failed.
+        Sets new attribute's value.
 
         @param nval: replaces current value by nval.
         @type nval: int
+        @raise IOError: if corresponding file in /proc/sys cannot be written.
         """
-        oldv = ctypes.c_int(0)
-        sizeo = ctypes.c_int(ctypes.sizeof(oldv))
-        newv = ctypes.c_int(nval)
-        sizen = ctypes.c_int(ctypes.sizeof(newv))
-        sysctl = self._inotify_wrapper._sysctl
-        res = sysctl(self._attr, 3,
-                     ctypes.c_voidp(ctypes.addressof(oldv)),
-                     ctypes.addressof(sizeo),
-                     ctypes.c_voidp(ctypes.addressof(newv)),
-                     sizen)
-        if res == -1:
-            raise OSError(self._inotify_wrapper.get_errno(),
-                          self._inotify_wrapper.str_errno())
+        with open(os.path.join(self._base, self._attr), 'w') as file_obj:
+            file_obj.write(str(nval) + '\n')
 
     value = property(get_val, set_val)
 
     def __repr__(self):
-        return '<%s=%d>' % (self._attrname, self.get_val())
+        return '<%s=%d>' % (self._attr, self.get_val())
 
 
 # Inotify's variables
 #
-# FIXME: currently these variables are only accessible when ctypes is used,
-#        otherwise there are set to None.
+# Note: may raise IOError if the corresponding value in /proc/sys
+#       cannot be accessed.
 #
-# read: myvar = max_queued_events.value
-# update: max_queued_events.value = 42
+# Examples:
+#  - read: myvar = max_queued_events.value
+#  - update: max_queued_events.value = 42
 #
 for attrname in ('max_queued_events', 'max_user_instances', 'max_user_watches'):
-    globals()[attrname] = SysCtlINotify.create(attrname)
+    globals()[attrname] = ProcINotify(attrname)
 
 
 class EventsCodes:
@@ -536,7 +486,7 @@ class _Event:
                 continue
             if attr == 'mask':
                 value = hex(getattr(self, attr))
-            elif isinstance(value, basestring) and not value:
+            elif isinstance(value, str) and not value:
                 value = "''"
             s += ' %s%s%s' % (output_format.field_name(attr),
                               output_format.punctuation('='),
@@ -628,7 +578,7 @@ class Event(_Event):
                                                              self.name))
             else:
                 self.pathname = os.path.abspath(self.path)
-        except AttributeError, err:
+        except AttributeError as err:
             # Usually it is not an error some events are perfectly valids
             # despite the lack of these attributes.
             log.debug(err)
@@ -718,8 +668,8 @@ class _SysProcessEvent(_ProcessEvent):
         and self._mv.
         """
         date_cur_ = datetime.now()
-        for seq in [self._mv_cookie, self._mv]:
-            for k in seq.keys():
+        for seq in (self._mv_cookie, self._mv):
+            for k in list(seq.keys()):
                 if (date_cur_ - seq[k][1]) > timedelta(minutes=1):
                     log.debug('Cleanup: deleting entry %s', seq[k][0])
                     del seq[k]
@@ -767,9 +717,9 @@ class _SysProcessEvent(_ProcessEvent):
                                 continue
                             rawevent = _RawEvent(created_dir_wd, flags, 0, name)
                             self._notifier.append_event(rawevent)
-                    except OSError, err:
-                        msg = "process_IN_CREATE, invalid directory %s: %s"
-                        log.debug(msg % (created_dir, str(err)))
+                    except OSError as err:
+                        msg = "process_IN_CREATE, invalid directory: %s"
+                        log.debug(msg % str(err))
         return self.process_default(raw_event)
 
     def process_IN_MOVED_FROM(self, raw_event):
@@ -1097,8 +1047,8 @@ class Stats(ProcessEvent):
         @type filename: string
         """
         flags = os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW|os.O_EXCL
-        fd = os.open(filename, flags, 0600)
-        os.write(fd, str(self))
+        fd = os.open(filename, flags, 0o0600)
+        os.write(fd, bytes(self.__str__(), locale.getpreferredencoding()))
         os.close(fd)
 
     def __str__(self, scale=45):
@@ -1107,7 +1057,7 @@ class Stats(ProcessEvent):
             return ''
 
         m = max(stats.values())
-        unity = float(scale) / m
+        unity = scale / m
         fmt = '%%-26s%%-%ds%%s' % (len(output_format.field_value('@' * scale))
                                    + 1)
         def func(x):
@@ -1149,7 +1099,7 @@ class Notifier:
         @type default_proc_fun: instance of ProcessEvent
         @param read_freq: if read_freq == 0, events are read asap,
                           if read_freq is > 0, this thread sleeps
-                          max(0, read_freq - timeout) seconds. But if
+                          max(0, read_freq - (timeout / 1000)) seconds. But if
                           timeout is None it may be different because
                           poll is blocking waiting for something to read.
         @type read_freq: int
@@ -1161,8 +1111,9 @@ class Notifier:
                           until the amount of events to read is >= threshold.
                           At least with read_freq set you might sleep.
         @type threshold: int
-        @param timeout:
-            https://docs.python.org/3/library/select.html#polling-objects
+        @param timeout: see read_freq above. If provided, it must be set in
+                        milliseconds. See
+                        https://docs.python.org/3/library/select.html#select.poll.poll
         @type timeout: int
         """
         # Watch Manager instance
@@ -1228,7 +1179,8 @@ class Notifier:
         milliseconds.
 
         @param timeout: If specified it overrides the corresponding instance
-                        attribute _timeout.
+                        attribute _timeout. timeout must be sepcified in
+                        milliseconds.
         @type timeout: int
 
         @return: New events to read.
@@ -1240,8 +1192,8 @@ class Notifier:
                 if timeout is None:
                     timeout = self._timeout
                 ret = self._pollobj.poll(timeout)
-            except select.error, err:
-                if err[0] == errno.EINTR:
+            except select.error as err:
+                if err.args[0] == errno.EINTR:
                     continue # interrupted, retry
                 else:
                     raise
@@ -1271,7 +1223,7 @@ class Notifier:
         try:
             # Read content from file
             r = os.read(self._fd, queue_size)
-        except Exception, msg:
+        except Exception as msg:
             raise NotifierError(msg)
         log.debug('Event queue size: %d', queue_size)
         rsum = 0  # counter
@@ -1281,9 +1233,11 @@ class Notifier:
             wd, mask, cookie, fname_len = struct.unpack('iIII',
                                                         r[rsum:rsum+s_size])
             # Retrieve name
-            fname, = struct.unpack('%ds' % fname_len,
+            bname, = struct.unpack('%ds' % fname_len,
                                    r[rsum + s_size:rsum + s_size + fname_len])
-            rawevent = _RawEvent(wd, mask, cookie, fname)
+            # FIXME: should we explictly call sys.getdefaultencoding() here ??
+            uname = bname.decode()
+            rawevent = _RawEvent(wd, mask, cookie, uname)
             if self._coalesce:
                 # Only enqueue new (unique) events.
                 raweventstr = str(rawevent)
@@ -1326,13 +1280,10 @@ class Notifier:
     def __daemonize(self, pid_file=None, stdin=os.devnull, stdout=os.devnull,
                     stderr=os.devnull):
         """
-        @param pid_file: file where the pid will be written. If pid_file=None
-                         the pid is written to
-                         /var/run/<sys.argv[0]|pyinotify>.pid, if pid_file=False
-                         no pid_file is written.
-        @param stdin:
-        @param stdout:
-        @param stderr: files associated to common streams.
+        pid_file: file where the pid will be written. If pid_file=None the pid
+                  is written to /var/run/<sys.argv[0]|pyinotify>.pid, if
+                  pid_file=False no pid_file is written.
+        stdin, stdout, stderr: files associated to common streams.
         """
         if pid_file is None:
             dirname = '/var/run/'
@@ -1354,7 +1305,7 @@ class Notifier:
                 if (pid == 0):
                     # child
                     os.chdir('/')
-                    os.umask(022)
+                    os.umask(0o022)
                 else:
                     # parent 2
                     os._exit(0)
@@ -1364,9 +1315,9 @@ class Notifier:
 
             fd_inp = os.open(stdin, os.O_RDONLY)
             os.dup2(fd_inp, 0)
-            fd_out = os.open(stdout, os.O_WRONLY|os.O_CREAT, 0600)
+            fd_out = os.open(stdout, os.O_WRONLY|os.O_CREAT, 0o0600)
             os.dup2(fd_out, 1)
-            fd_err = os.open(stderr, os.O_WRONLY|os.O_CREAT, 0600)
+            fd_err = os.open(stderr, os.O_WRONLY|os.O_CREAT, 0o0600)
             os.dup2(fd_err, 2)
 
         # Detach task
@@ -1375,8 +1326,9 @@ class Notifier:
         # Write pid
         if pid_file != False:
             flags = os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW|os.O_EXCL
-            fd_pid = os.open(pid_file, flags, 0600)
-            os.write(fd_pid, str(os.getpid()) + '\n')
+            fd_pid = os.open(pid_file, flags, 0o0600)
+            os.write(fd_pid,  bytes(str(os.getpid()) + '\n',
+                                    locale.getpreferredencoding()))
             os.close(fd_pid)
             # Register unlink function
             atexit.register(lambda : os.unlink(pid_file))
@@ -1441,9 +1393,12 @@ class Notifier:
         Close inotify's instance (close its file descriptor).
         It destroys all existing watches, pending events,...
         This method is automatically called at the end of loop().
+        Afterward it is invalid to access this instance.
         """
-        self._pollobj.unregister(self._fd)
-        os.close(self._fd)
+        if self._fd is not None:
+            self._pollobj.unregister(self._fd)
+            os.close(self._fd)
+            self._fd = None
         self._sys_proc_fun = None
 
 
@@ -1468,7 +1423,7 @@ class ThreadedNotifier(threading.Thread, Notifier):
         @type default_proc_fun: instance of ProcessEvent
         @param read_freq: if read_freq == 0, events are read asap,
                           if read_freq is > 0, this thread sleeps
-                          max(0, read_freq - timeout) seconds.
+                          max(0, read_freq - (timeout / 1000)) seconds.
         @type read_freq: int
         @param threshold: File descriptor will be read only if the accumulated
                           size to read becomes >= threshold. If != 0, you likely
@@ -1478,8 +1433,9 @@ class ThreadedNotifier(threading.Thread, Notifier):
                           until the amount of events to read is >= threshold. At
                           least with read_freq you might sleep.
         @type threshold: int
-        @param timeout:
-            https://docs.python.org/3/library/select.html#polling-objects
+        @param timeout: see read_freq above. If provided, it must be set in
+                        milliseconds. See
+                        https://docs.python.org/3/library/select.html#select.poll.poll
         @type timeout: int
         """
         # Init threading base class
@@ -1498,7 +1454,7 @@ class ThreadedNotifier(threading.Thread, Notifier):
         Stop notifier's loop. Stop notification. Join the thread.
         """
         self._stop_event.set()
-        os.write(self._pipe[1], 'stop')
+        os.write(self._pipe[1], b'stop')
         threading.Thread.join(self)
         Notifier.stop(self)
         self._pollobj.unregister(self._pipe[0])
@@ -1699,7 +1655,6 @@ class Watch:
 class ExcludeFilter:
     """
     ExcludeFilter is an exclusion filter.
-
     """
     def __init__(self, arg_lst):
         """
@@ -1731,16 +1686,13 @@ class ExcludeFilter:
 
     def _load_patterns_from_file(self, filename):
         lst = []
-        file_obj = file(filename, 'r')
-        try:
+        with open(filename, 'r') as file_obj:
             for line in file_obj.readlines():
                 # Trim leading an trailing whitespaces
                 pattern = line.strip()
                 if not pattern or pattern.startswith('#'):
                     continue
                 lst.append(pattern)
-        finally:
-            file_obj.close()
         return lst
 
     def _match(self, regex, path):
@@ -1764,7 +1716,6 @@ class WatchManagerError(Exception):
     """
     WatchManager Exception. Raised on error encountered on watches
     operations.
-
     """
     def __init__(self, msg, wmd):
         """
@@ -1851,7 +1802,7 @@ class WatchManager:
         """
         try:
             del self._wmd[wd]
-        except KeyError, err:
+        except KeyError as err:
             log.error('Cannot delete unknown watch descriptor %s' % str(err))
 
     @property
@@ -1868,13 +1819,7 @@ class WatchManager:
         """
         Format path to its internal (stored in watch manager) representation.
         """
-        # Unicode strings are converted back to strings, because it seems
-        # that inotify_add_watch from ctypes does not work well when
-        # it receives an ctypes.create_unicode_buffer instance as argument.
-        # Therefore even wd are indexed with bytes string and not with
-        # unicode paths.
-        if isinstance(path, unicode):
-            path = path.encode(sys.getfilesystemencoding())
+        # path must be a unicode string (str) and is just normalized.
         return os.path.normpath(path)
 
     def __add_watch(self, path, mask, proc_fun, auto_add, exclude_filter):
@@ -1890,13 +1835,14 @@ class WatchManager:
             return wd
         watch = Watch(wd=wd, path=path, mask=mask, proc_fun=proc_fun,
                       auto_add=auto_add, exclude_filter=exclude_filter)
+        # wd are _always_ indexed with their original unicode paths in wmd.
         self._wmd[wd] = watch
         log.debug('New %s', watch)
         return wd
 
     def __glob(self, path, do_glob):
         if do_glob:
-            return glob(path)
+            return glob.iglob(path)
         else:
             return [path]
 
@@ -1907,11 +1853,8 @@ class WatchManager:
         Add watch(s) on the provided |path|(s) with associated |mask| flag
         value and optionally with a processing |proc_fun| function and
         recursive flag |rec| set to True.
-        Ideally |path| components should not be unicode objects. Note that
-        although unicode paths are accepted there are converted to byte
-        strings before a watch is put on that path. The encoding used for
-        converting the unicode object is given by sys.getfilesystemencoding().
-        If |path| si already watched it is ignored, but if it is called with
+        All |path| components _must_ be str (i.e. unicode) objects.
+        If |path| is already watched it is ignored, but if it is called with
         option rec=True a watch is put on each one of its not-watched
         subdirectory.
 
@@ -1945,10 +1888,9 @@ class WatchManager:
                                the class' constructor.
         @type exclude_filter: callable object
         @return: dict of paths associated to watch descriptors. A wd value
-                 is positive if the watch was added sucessfully,
-                 otherwise the value is negative. If the path was invalid
-                 or was already watched it is not included into this returned
-                 dictionary.
+                 is positive if the watch was added sucessfully, otherwise
+                 the value is negative. If the path was invalid or was already
+                 watched it is not included into this returned dictionary.
         @rtype: dict of {str: int}
         """
         ret_ = {} # return {path: wd, ...}
@@ -1958,6 +1900,11 @@ class WatchManager:
 
         # normalize args as list elements
         for npath in self.__format_param(path):
+            # Require that path be a unicode string
+            if not isinstance(npath, str):
+                ret_[path] = -3
+                continue
+
             # unix pathname pattern expansion
             for apath in self.__glob(npath, do_glob):
                 # recursively list subdirs according to rec param
@@ -2242,7 +2189,6 @@ class WatchManager:
                              "Make watch manager ignoring new events.")
 
 
-
 class RawOutputFormat:
     """
     Format string representations.
Signature · 1 line
2.5.0
#2 lore raw

PATCH 3/28 bitbake: Drop futures usage since we're python 3

In reply to Richard Purdie
---
 lib/bb/cooker.py                   | 2 +-
 lib/bb/exceptions.py               | 2 +-
 lib/bb/fetch2/__init__.py          | 2 --
 lib/bb/fetch2/perforce.py          | 1 -
 lib/bb/parse/ast.py                | 3 +--
 lib/bb/parse/parse_py/BBHandler.py | 2 +-
 6 files changed, 4 insertions(+), 8 deletions(-)
lib/bb/cooker.py +1 -1
index fb86446..11f17ef 100644
@@ -22,7 +22,7 @@
 # with this program; if not, write to the Free Software Foundation, Inc.,
 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
-from __future__ import print_function
+
 import sys, os, glob, os.path, re, time
 import atexit
 import itertools
lib/bb/exceptions.py +1 -1
index f182c8f..eadfc57 100644
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+
 import inspect
 import traceback
 import bb.namedtuple_with_abc
lib/bb/fetch2/__init__.py +0 -2
index 7d2f350..14fe3c7 100644
@@ -25,8 +25,6 @@ BitBake build tools.
 #
 # Based on functions from the base bb module, Copyright 2003 Holger Schurig
 
-from __future__ import absolute_import
-from __future__ import print_function
 import os, re
 import signal
 import logging
lib/bb/fetch2/perforce.py +0 -1
index 3a10c7c..1aef246 100644
@@ -25,7 +25,6 @@ BitBake build tools.
 #
 # Based on functions from the base bb module, Copyright 2003 Holger Schurig
 
-from future_builtins import zip
 import os
 import subprocess
 import logging
lib/bb/parse/ast.py +1 -2
index 5f55af5..bc3a2f8 100644
@@ -21,8 +21,7 @@
 # with this program; if not, write to the Free Software Foundation, Inc.,
 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
-from __future__ import absolute_import
-from future_builtins import filter
+
 import re
 import string
 import logging
lib/bb/parse/parse_py/BBHandler.py +1 -1
index ef72c37..c54a079 100644
@@ -25,7 +25,7 @@
 # with this program; if not, write to the Free Software Foundation, Inc.,
 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
-from __future__ import absolute_import
+
 import re, bb, os
 import logging
 import bb.build, bb.utils
Signature · 1 line
2.5.0
#3 lore raw

PATCH 4/28 bitbake: Convert to python 3 megacommit This needs breaking up into smaller changes.

In reply to Richard Purdie
---
 bin/bitbake                      |   5 +-
 bin/bitbake-diffsigs             |   4 +-
 bin/bitbake-dumpsig              |   4 +-
 bin/bitbake-layers               |   5 +-
 bin/bitbake-prserv               |   2 +-
 bin/bitbake-selftest             |   2 +-
 bin/bitbake-worker               |  60 ++++++++++----------
 bin/bitdoc                       |   2 +-
 bin/image-writer                 |   8 ++-
 bin/toaster-eventreplay          |   2 +-
 contrib/dump_cache.py            |   2 +-
 lib/bb/COW.py                    |  44 +++++++--------
 lib/bb/__init__.py               |   2 +-
 lib/bb/build.py                  |  13 ++---
 lib/bb/cache.py                  |  18 ++----
 lib/bb/checksum.py               |   9 +--
 lib/bb/codeparser.py             |  15 ++---
 lib/bb/command.py                |   2 +-
 lib/bb/cooker.py                 |  38 ++++++-------
 lib/bb/data_smart.py             |   4 +-
 lib/bb/event.py                  |   9 +--
 lib/bb/exceptions.py             |   2 +-
 lib/bb/fetch2/__init__.py        |  36 ++++++------
 lib/bb/fetch2/local.py           |   4 +-
 lib/bb/fetch2/npm.py             |   6 +-
 lib/bb/fetch2/perforce.py        |   2 +-
 lib/bb/fetch2/sftp.py            |   8 +--
 lib/bb/fetch2/ssh.py             |   6 +-
 lib/bb/fetch2/wget.py            |  48 ++++++++--------
 lib/bb/main.py                   |  11 ++--
 lib/bb/msg.py                    |   2 +-
 lib/bb/parse/ast.py              |  18 +++---
 lib/bb/persist_data.py           |  10 ++--
 lib/bb/process.py                |  36 ++++++++----
 lib/bb/providers.py              |   2 +-
 lib/bb/pysh/builtin.py           |   2 +-
 lib/bb/pysh/interp.py            |   4 +-
 lib/bb/pysh/pyshlex.py           |   2 +-
 lib/bb/pysh/pyshyacc.py          |   4 +-
 lib/bb/runqueue.py               | 117 +++++++++++++++++++--------------------
 lib/bb/server/process.py         |   8 +--
 lib/bb/server/xmlrpc.py          |  48 ++++++++--------
 lib/bb/siggen.py                 |  19 +++----
 lib/bb/taskdata.py               |  12 ++--
 lib/bb/tests/codeparser.py       |   4 +-
 lib/bb/tests/data.py             |  12 ++--
 lib/bb/tests/parse.py            |   2 +-
 lib/bb/ui/crumbs/hobwidget.py    |   2 +-
 lib/bb/ui/crumbs/progressbar.py  |   6 +-
 lib/bb/ui/crumbs/runningbuild.py |  12 ++--
 lib/bb/ui/goggle.py              |  11 +++-
 lib/bb/ui/knotty.py              |   6 +-
 lib/bb/ui/ncurses.py             |   8 +--
 lib/bb/ui/uievent.py             |   4 +-
 lib/bb/utils.py                  |  20 +++----
 lib/bblayers/action.py           |   2 +-
 lib/bblayers/common.py           |   2 +-
 lib/bblayers/layerindex.py       |  12 ++--
 lib/bblayers/query.py            |   4 +-
 lib/codegen.py                   |   8 +--
 lib/ply/yacc.py                  |   2 +
 lib/prserv/db.py                 |   2 +-
 lib/prserv/serv.py               |  14 ++---
 63 files changed, 390 insertions(+), 400 deletions(-)
bin/bitbake +4 -1
index bba87b0..9813a08 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # ex:ts=4:sw=4:sts=4:et
 # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
 #
@@ -35,6 +35,9 @@ except RuntimeError as exc:
 from bb import cookerdata
 from bb.main import bitbake_main, BitBakeConfigParameters, BBMainException
 
+if sys.getfilesystemencoding() != "utf-8":
+    sys.exit("Please use a locale setting which supports utf-8.\nPython can't change the filesystem locale after loading so we need a utf-8 when python starts or things won't work.")
+
 __version__ = "1.31.0"
 
 if __name__ == "__main__":
bin/bitbake-diffsigs +2 -2
index 67c60db..3b6ef88 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 # bitbake-diffsigs
 # BitBake task signature data comparison utility
@@ -24,6 +24,7 @@ import warnings
 import fnmatch
 import optparse
 import logging
+import pickle
 
 sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])), 'lib'))
 
@@ -121,7 +122,6 @@ else:
     if len(args) == 1:
         parser.print_help()
     else:
-        import cPickle
         try:
             if len(args) == 2:
                 output = bb.siggen.dump_sigfile(sys.argv[1])
bin/bitbake-dumpsig +2 -2
index ffaed1f..58ba1ca 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 # bitbake-dumpsig
 # BitBake task signature dump utility
@@ -23,6 +23,7 @@ import sys
 import warnings
 import optparse
 import logging
+import pickle
 
 sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(sys.argv[0])), 'lib'))
 
@@ -51,7 +52,6 @@ options, args = parser.parse_args(sys.argv)
 if len(args) == 1:
     parser.print_help()
 else:
-    import cPickle
     try:
         output = bb.siggen.dump_sigfile(args[1])
     except IOError as e:
bin/bitbake-layers +2 -3
index d8ffa95..0c973df 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 # This script has subcommands which operate against your bitbake layers, either
 # displaying useful information, or acting against them.
@@ -48,7 +48,6 @@ def logger_create(name, output=sys.stderr):
     logger.setLevel(logging.INFO)
     return logger
 
-
 def logger_setup_color(logger, color='auto'):
     from bb.msg import BBLogFormatter
     console = logging.StreamHandler(sys.stdout)
@@ -61,7 +60,6 @@ def logger_setup_color(logger, color='auto'):
 
 logger = logger_create('bitbake-layers', sys.stdout)
 
-
 def main():
     parser = argparse.ArgumentParser(
         description="BitBake layers utility",
@@ -78,6 +76,7 @@ def main():
     parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS,
                         help='show this help message and exit')
     subparsers = parser.add_subparsers(title='subcommands', metavar='<subcommand>')
+    subparsers.required = True
 
     if global_args.debug:
         logger.setLevel(logging.DEBUG)
bin/bitbake-prserv +1 -1
index 0382144..f38d2dd 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 import os
 import sys,logging
 import optparse
bin/bitbake-selftest +1 -1
index 462eb1b..1e6f35e 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 # Copyright (C) 2012 Richard Purdie
 #
bin/bitbake-worker +31 -29

157 lines not on this page · raw message

bin/bitdoc +1 -1
index defb3dd..2744678 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # ex:ts=4:sw=4:sts=4:et
 # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
 #
bin/image-writer +6 -2
index e30ab45..7ab1d8c 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 # Copyright (c) 2012 Wind River Systems, Inc.
 #
@@ -24,9 +24,13 @@ try:
 except RuntimeError as exc:
     sys.exit(str(exc))
 
+from gi import pygtkcompat
+
+pygtkcompat.enable()
+pygtkcompat.enable_gtk(version='3.0')
+
 import gtk
 import optparse
-import pygtk
 
 from bb.ui.crumbs.hobwidget import HobAltButton, HobButton
 from bb.ui.crumbs.hig.crumbsmessagedialog import CrumbsMessageDialog
bin/toaster-eventreplay +1 -1
index 615a7ae..bdddb90 100755
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 # ex:ts=4:sw=4:sts=4:et
 # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
 #
contrib/dump_cache.py +1 -1
index 97c5463..a1f09b4 100755
@@ -29,7 +29,7 @@ import warnings
 sys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), '../lib'))
 from bb.cache import CoreRecipeInfo
 
-import cPickle as pickle
+import pickle as pickle
 
 def main(argv=None):
     """
lib/bb/COW.py +20 -24

150 lines not on this page · raw message

lib/bb/__init__.py +1 -1
index 4ae6b8a..6b85984 100644
@@ -84,7 +84,7 @@ def plain(*args):
     mainlogger.plain(''.join(args))
 
 def debug(lvl, *args):
-    if isinstance(lvl, basestring):
+    if isinstance(lvl, str):
         mainlogger.warning("Passed invalid debug level '%s' to bb.debug", lvl)
         args = (lvl,) + args
         lvl = 1
lib/bb/build.py +6 -7
index 9854553..e016ae3 100644
@@ -35,8 +35,7 @@ import stat
 import bb
 import bb.msg
 import bb.process
-from contextlib import nested
-from bb import event, utils
+from bb import data, event, utils
 
 bblogger = logging.getLogger('BitBake')
 logger = logging.getLogger('BitBake.Build')
@@ -328,7 +327,7 @@ trap '' 0
 exit $ret
 ''')
 
-    os.chmod(runfile, 0775)
+    os.chmod(runfile, 0o775)
 
     cmd = runfile
     if d.getVarFlag(func, 'fakeroot', False):
@@ -342,12 +341,12 @@ exit $ret
         logfile = sys.stdout
 
     def readfifo(data):
-        lines = data.split('\0')
+        lines = data.split(b'\0')
         for line in lines:
-            splitval = line.split(' ', 1)
+            splitval = line.split(b' ', 1)
             cmd = splitval[0]
             if len(splitval) > 1:
-                value = splitval[1]
+                value = splitval[1].decode("utf-8")
             else:
                 value = ''
             if cmd == 'bbplain':
@@ -375,7 +374,7 @@ exit $ret
     if os.path.exists(fifopath):
         os.unlink(fifopath)
     os.mkfifo(fifopath)
-    with open(fifopath, 'r+') as fifo:
+    with open(fifopath, 'r+b', buffering=0) as fifo:
         try:
             bb.debug(2, "Executing shell function %s" % func)
 
lib/bb/cache.py +6 -12
index 393d541..96abd71 100644
@@ -28,21 +28,15 @@
 # with this program; if not, write to the Free Software Foundation, Inc.,
 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
-
 import os
+import sys
 import logging
+import pickle
 from collections import defaultdict
 import bb.utils
 
 logger = logging.getLogger("BitBake.Cache")
 
-try:
-    import cPickle as pickle
-except ImportError:
-    import pickle
-    logger.info("Importing cPickle failed. "
-                "Falling back to a very slow implementation.")
-
 __cache_version__ = "150"
 
 def getCacheFile(path, filename, data_hash):
@@ -80,7 +74,7 @@ class RecipeInfoCommon(object):
         out_dict = dict((var, metadata.getVarFlag(var, flag, True))
                     for var in varlist)
         if squash:
-            return dict((k,v) for (k,v) in out_dict.iteritems() if v)
+            return dict((k,v) for (k,v) in out_dict.items() if v)
         else:
             return out_dict
 
@@ -240,7 +234,7 @@ class CoreRecipeInfo(RecipeInfoCommon):
         cachedata.universe_target.append(self.pn)
 
         cachedata.hashfn[fn] = self.hashfilename
-        for task, taskhash in self.basetaskhashes.iteritems():
+        for task, taskhash in self.basetaskhashes.items():
             identifier = '%s.%s' % (fn, task)
             cachedata.basetaskhash[identifier] = taskhash
 
@@ -404,7 +398,7 @@ class Cache(object):
         infos = []
         datastores = cls.load_bbfile(filename, appends, configdata)
         depends = []
-        for variant, data in sorted(datastores.iteritems(),
+        for variant, data in sorted(datastores.items(),
                                     key=lambda i: i[0],
                                     reverse=True):
             virtualfn = cls.realfn2virtual(filename, variant)
@@ -616,7 +610,7 @@ class Cache(object):
         pickler_dict['CoreRecipeInfo'].dump(bb.__version__)
 
         try:
-            for key, info_array in self.depends_cache.iteritems():
+            for key, info_array in self.depends_cache.items():
                 for info in info_array:
                     if isinstance(info, RecipeInfoCommon):
                         cache_class_name = info.__class__.__name__
lib/bb/checksum.py +1 -8
index 2ec964d..be4ab68 100644
@@ -19,20 +19,13 @@ import glob
 import operator
 import os
 import stat
+import pickle
 import bb.utils
 import logging
 from bb.cache import MultiProcessCache
 
 logger = logging.getLogger("BitBake.Cache")
 
-try:
-    import cPickle as pickle
-except ImportError:
-    import pickle
-    logger.info("Importing cPickle failed. "
-                "Falling back to a very slow implementation.")
-
-
 # mtime cache (non-persistent)
 # based upon the assumption that files do not change during bitbake run
 class FileMtimeCache(object):
lib/bb/codeparser.py +5 -10
index 70b0a8d..b1d067a 100644
@@ -1,22 +1,17 @@
 import ast
+import sys
 import codegen
 import logging
+import pickle
+import bb.pysh as pysh
 import os.path
 import bb.utils, bb.data
 from itertools import chain
-from pysh import pyshyacc, pyshlex, sherrors
+from bb.pysh import pyshyacc, pyshlex, sherrors
 from bb.cache import MultiProcessCache
 
-
 logger = logging.getLogger('BitBake.CodeParser')
 
-try:
-    import cPickle as pickle
-except ImportError:
-    import pickle
-    logger.info('Importing cPickle failed.  Falling back to a very slow implementation.')
-
-
 def check_indent(codestr):
     """If the code is indented, add a top level piece of code to 'remove' the indentation"""
 
@@ -68,7 +63,7 @@ class SetCache(object):
         
         new = []
         for i in items:
-            new.append(intern(i))
+            new.append(sys.intern(i))
         s = frozenset(new)
         if hash(s) in self.setcache:
             return self.setcache[hash(s)]
lib/bb/command.py +1 -1
index 0559ffc..caa3e4d 100644
@@ -110,7 +110,7 @@ class Command:
             return False
         except SystemExit as exc:
             arg = exc.args[0]
-            if isinstance(arg, basestring):
+            if isinstance(arg, str):
                 self.finishAsyncCommand(arg)
             else:
                 self.finishAsyncCommand("Exited with %s" % arg)
lib/bb/cooker.py +19 -19
index 11f17ef..2154ef4 100644
@@ -30,13 +30,13 @@ import logging
 import multiprocessing
 import sre_constants
 import threading
-from cStringIO import StringIO
+from io import StringIO
 from contextlib import closing
 from functools import wraps
 from collections import defaultdict
 import bb, bb.exceptions, bb.command
 from bb import utils, data, parse, event, cache, providers, taskdata, runqueue, build
-import Queue
+import queue
 import signal
 import subprocess
 import errno
@@ -65,7 +65,7 @@ class CollectionError(bb.BBHandledException):
     """
 
 class state:
-    initial, parsing, running, shutdown, forceshutdown, stopped, error = range(7)
+    initial, parsing, running, shutdown, forceshutdown, stopped, error = list(range(7))
 
     @classmethod
     def get_name(cls, code):
@@ -93,7 +93,7 @@ class SkippedPackage:
 
 
 class CookerFeatures(object):
-    _feature_list = [HOB_EXTRA_CACHES, BASEDATASTORE_TRACKING, SEND_SANITYEVENTS] = range(3)
+    _feature_list = [HOB_EXTRA_CACHES, BASEDATASTORE_TRACKING, SEND_SANITYEVENTS] = list(range(3))
 
     def __init__(self):
         self._features=set()
@@ -110,8 +110,8 @@ class CookerFeatures(object):
     def __iter__(self):
         return self._features.__iter__()
 
-    def next(self):
-        return self._features.next()
+    def __next__(self):
+        return next(self._features)
 
 
 #============================================================================#
@@ -726,13 +726,13 @@ class BBCooker:
         depend_tree['providermap'] = {}
         depend_tree["layer-priorities"] = self.recipecache.bbfile_config_priorities
 
-        for name, fn in taskdata.get_providermap().iteritems():
+        for name, fn in list(taskdata.get_providermap().items()):
             pn = self.recipecache.pkg_fn[fn]
             if name != pn:
                 version = "%s:%s-%s" % self.recipecache.pkg_pepvpr[fn]
                 depend_tree['providermap'][name] = (pn, version)
 
-        for task in xrange(len(rq.rqdata.runq_fnid)):
+        for task in range(len(rq.rqdata.runq_fnid)):
             taskname = rq.rqdata.runq_task[task]
             fnid = rq.rqdata.runq_fnid[task]
             fn = taskdata.fn_index[fnid]
@@ -807,7 +807,7 @@ class BBCooker:
         _, taskdata = self.prepareTreeData(pkgs_to_build, task)
         tasks_fnid = []
         if len(taskdata.tasks_name) != 0:
-            for task in xrange(len(taskdata.tasks_name)):
+            for task in range(len(taskdata.tasks_name)):
                 tasks_fnid.append(taskdata.tasks_fnid[task])
 
         seen_fnids = []
@@ -825,7 +825,7 @@ class BBCooker:
                 cachefields = getattr(cache_class, 'cachefields', [])
                 extra_info = extra_info + cachefields
 
-        for task in xrange(len(tasks_fnid)):
+        for task in range(len(tasks_fnid)):
             fnid = tasks_fnid[task]
             fn = taskdata.fn_index[fnid]
             pn = self.recipecache.pkg_fn[fn]
@@ -953,7 +953,7 @@ class BBCooker:
         # Determine which bbappends haven't been applied
 
         # First get list of recipes, including skipped
-        recipefns = self.recipecache.pkg_fn.keys()
+        recipefns = list(self.recipecache.pkg_fn.keys())
         recipefns.extend(self.skiplist.keys())
 
         # Work out list of bbappends that have been applied
@@ -1152,7 +1152,7 @@ class BBCooker:
                         deplist = bb.utils.explode_dep_versions2(deps)
                     except bb.utils.VersionStringException as vse:
                         bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse)))
-                    for dep, oplist in deplist.iteritems():
+                    for dep, oplist in list(deplist.items()):
                         if dep in collection_list:
                             for opstr in oplist:
                                 layerver = self.data.getVar("LAYERVERSION_%s" % dep, True)
@@ -1888,7 +1888,7 @@ class Feeder(multiprocessing.Process):
         while True:
             try:
                 quit = self.quit.get_nowait()
-            except Queue.Empty:
+            except queue.Empty:
                 pass
             else:
                 if quit == 'cancel':
@@ -1902,7 +1902,7 @@ class Feeder(multiprocessing.Process):
 
             try:
                 self.to_parsers.put(job, timeout=0.5)
-            except Queue.Full:
+            except queue.Full:
                 self.jobs.insert(0, job)
                 continue
 
@@ -1942,7 +1942,7 @@ class Parser(multiprocessing.Process):
         while True:
             try:
                 self.quit.get_nowait()
-            except Queue.Empty:
+            except queue.Empty:
                 pass
             else:
                 self.results.cancel_join_thread()
@@ -1953,7 +1953,7 @@ class Parser(multiprocessing.Process):
             else:
                 try:
                     job = self.jobs.get(timeout=0.25)
-                except Queue.Empty:
+                except queue.Empty:
                     continue
 
                 if job is None:
@@ -1962,7 +1962,7 @@ class Parser(multiprocessing.Process):
 
             try:
                 self.results.put(result, timeout=0.25)
-            except Queue.Full:
+            except queue.Full:
                 pending.append(result)
 
     def parse(self, filename, appends, caches_array):
@@ -2115,7 +2115,7 @@ class CookerParser(object):
 
             try:
                 result = self.result_queue.get(timeout=0.25)
-            except Queue.Empty:
+            except queue.Empty:
                 pass
             else:
                 value = result[1]
@@ -2128,7 +2128,7 @@ class CookerParser(object):
         result = []
         parsed = None
         try:
-            parsed, result = self.results.next()
+            parsed, result = next(self.results)
         except StopIteration:
             self.shutdown()
             return False
lib/bb/data_smart.py +2 -2
index 2ab884b..2a61386 100644
@@ -372,7 +372,7 @@ class DataSmart(MutableMapping):
 
     def expandWithRefs(self, s, varname):
 
-        if not isinstance(s, basestring): # sanity check
+        if not isinstance(s, str): # sanity check
             return VariableParse(varname, self, s)
 
         if varname and varname in self.expand_cache:
@@ -966,4 +966,4 @@ class DataSmart(MutableMapping):
                     data.update({i:value})
 
         data_str = str([(k, data[k]) for k in sorted(data.keys())])
-        return hashlib.md5(data_str).hexdigest()
+        return hashlib.md5(data_str.encode("utf-8")).hexdigest()
lib/bb/event.py +3 -6
index 29b14f6..6fb3712 100644
@@ -24,10 +24,7 @@ BitBake build tools.
 
 import os, sys
 import warnings
-try:
-    import cPickle as pickle
-except ImportError:
-    import pickle
+import pickle
 import logging
 import atexit
 import traceback
@@ -107,7 +104,7 @@ def fire_class_handlers(event, d):
 
     eid = str(event.__class__)[8:-2]
     evt_hmap = _event_handler_map.get(eid, {})
-    for name, handler in _handlers.iteritems():
+    for name, handler in list(_handlers.items()):
         if name in _catchall_handlers or name in evt_hmap:
             if _eventfilter:
                 if not _eventfilter(name, handler, event, d):
@@ -192,7 +189,7 @@ def register(name, handler, mask=None, filename=None, lineno=None):
 
     if handler is not None:
         # handle string containing python code
-        if isinstance(handler, basestring):
+        if isinstance(handler, str):
             tmp = "def %s(e):\n%s" % (name, handler)
             try:
                 code = bb.methodpool.compile_cache(tmp)
lib/bb/exceptions.py +1 -1
index eadfc57..cd71343 100644
@@ -86,6 +86,6 @@ def format_exception(etype, value, tb, context=1, limit=None, formatter=None):
 
 def to_string(exc):
     if isinstance(exc, SystemExit):
-        if not isinstance(exc.code, basestring):
+        if not isinstance(exc.code, str):
             return 'Exited with "%d"' % exc.code
     return str(exc)
lib/bb/fetch2/__init__.py +16 -20
index 14fe3c7..be01bdb 100644
@@ -28,27 +28,23 @@ BitBake build tools.
 import os, re
 import signal
 import logging
-import urllib
-import urlparse
+import urllib.request, urllib.parse, urllib.error
+if 'git' not in urllib.parse.uses_netloc:
+    urllib.parse.uses_netloc.append('git')
+import operator
 import collections
+import subprocess
+import pickle
 import bb.persist_data, bb.utils
 import bb.checksum
 from bb import data
 import bb.process
-import subprocess
 
 __version__ = "2"
 _checksum_cache = bb.checksum.FileChecksumCache()
 
 logger = logging.getLogger("BitBake.Fetcher")
 
-try:
-    import cPickle as pickle
-except ImportError:
-    import pickle
-    logger.info("Importing cPickle failed. "
-                "Falling back to a very slow implementation.")
-
 class BBFetchException(Exception):
     """Class all fetch exceptions inherit from"""
     def __init__(self, message):
@@ -230,14 +226,14 @@ class URI(object):
         # them are not quite RFC compliant.
         uri, param_str = (uri.split(";", 1) + [None])[:2]
 
-        urlp = urlparse.urlparse(uri)
+        urlp = urllib.parse.urlparse(uri)
         self.scheme = urlp.scheme
 
         reparse = 0
 
         # Coerce urlparse to make URI scheme use netloc
-        if not self.scheme in urlparse.uses_netloc:
-            urlparse.uses_params.append(self.scheme)
+        if not self.scheme in urllib.parse.uses_netloc:
+            urllib.parse.uses_params.append(self.scheme)
             reparse = 1
 
         # Make urlparse happy(/ier) by converting local resources
@@ -248,7 +244,7 @@ class URI(object):
             reparse = 1
 
         if reparse:
-            urlp = urlparse.urlparse(uri)
+            urlp = urllib.parse.urlparse(uri)
 
         # Identify if the URI is relative or not
         if urlp.scheme in self._relative_schemes and \
@@ -264,7 +260,7 @@ class URI(object):
             if urlp.password:
                 self.userinfo += ':%s' % urlp.password
 
-        self.path = urllib.unquote(urlp.path)
+        self.path = urllib.parse.unquote(urlp.path)
 
         if param_str:
             self.params = self._param_str_split(param_str, ";")
@@ -312,11 +308,11 @@ class URI(object):
 
     @property
     def path_quoted(self):
-        return urllib.quote(self.path)
+        return urllib.parse.quote(self.path)
 
     @path_quoted.setter
     def path_quoted(self, path):
-        self.path = urllib.unquote(path)
+        self.path = urllib.parse.unquote(path)
 
     @property
     def path(self):
@@ -398,7 +394,7 @@ def decodeurl(url):
                 s1, s2 = s.split('=')
                 p[s1] = s2
 
-    return type, host, urllib.unquote(path), user, pswd, p
+    return type, host, urllib.parse.unquote(path), user, pswd, p
 
 def encodeurl(decoded):
     """Encodes a URL from tokens (scheme, network location, path,
@@ -422,7 +418,7 @@ def encodeurl(decoded):
     # Standardise path to ensure comparisons work
     while '//' in path:
         path = path.replace("//", "/")
-    url += "%s" % urllib.quote(path)
+    url += "%s" % urllib.parse.quote(path)
     if p:
         for parm in p:
             url += ";%s=%s" % (parm, p[parm])
@@ -1735,7 +1731,7 @@ class FetchConnectionCache(object):
             del self.cache[cn]
 
     def close_connections(self):
-        for cn in self.cache.keys():
+        for cn in list(self.cache.keys()):
             self.cache[cn].close()
             del self.cache[cn]
 
lib/bb/fetch2/local.py +2 -2
index 303a52b..51ca78d 100644
@@ -26,7 +26,7 @@ BitBake build tools.
 # Based on functions from the base bb module, Copyright 2003 Holger Schurig
 
 import os
-import urllib
+import urllib.request, urllib.parse, urllib.error
 import bb
 import bb.utils
 from   bb import data
@@ -42,7 +42,7 @@ class Local(FetchMethod):
 
     def urldata_init(self, ud, d):
         # We don't set localfile as for this fetcher the file is already local!
-        ud.decodedurl = urllib.unquote(ud.url.split("://")[1].split(";")[0])
+        ud.decodedurl = urllib.parse.unquote(ud.url.split("://")[1].split(";")[0])
         ud.basename = os.path.basename(ud.decodedurl)
         ud.basepath = ud.decodedurl
         ud.needdonestamp = False
lib/bb/fetch2/npm.py +3 -3
index d9e46b2..2fd4303 100644
@@ -20,7 +20,7 @@ Usage in the recipe:
 
 import os
 import sys
-import urllib
+import urllib.request, urllib.parse, urllib.error
 import json
 import subprocess
 import signal
@@ -196,9 +196,9 @@ class Npm(FetchMethod):
                 optdepsfound[dep] = dependencies[dep]
             else:
                 depsfound[dep] = dependencies[dep]
-        for dep, version in optdepsfound.iteritems():
+        for dep, version in optdepsfound.items():
             self._getdependencies(dep, data[pkg]['deps'], version, d, ud, optional=True)
-        for dep, version in depsfound.iteritems():
+        for dep, version in depsfound.items():
             self._getdependencies(dep, data[pkg]['deps'], version, d, ud)
 
     def _getshrinkeddependencies(self, pkg, data, version, d, ud, lockdown, manifest):
lib/bb/fetch2/perforce.py +1 -1
index 1aef246..ce3cda2 100644
@@ -61,7 +61,7 @@ class Perforce(FetchMethod):
                     keys.append(key)
                     values.append(value)
 
-            parm = dict(zip(keys, values))
+            parm = dict(list(zip(keys, values)))
         path = "//" + path.split(';')[0]
         host += ":%s" % (port)
         parm["cset"] = Perforce.getcset(d, path, host, user, pswd, parm)
lib/bb/fetch2/sftp.py +3 -5
index cb2f753..7989fcc 100644
@@ -61,8 +61,7 @@ SRC_URI = "sftp://[email protected]/dir/path.file.txt"
 
 import os
 import bb
-import urllib
-import commands
+import urllib.request, urllib.parse, urllib.error
 from bb import data
 from bb.fetch2 import URI
 from bb.fetch2 import FetchMethod
@@ -93,7 +92,7 @@ class SFTP(FetchMethod):
         else:
             ud.basename = os.path.basename(ud.path)
 
-        ud.localfile = data.expand(urllib.unquote(ud.basename), d)
+        ud.localfile = data.expand(urllib.parse.unquote(ud.basename), d)
 
     def download(self, ud, d):
         """Fetch urls"""
@@ -121,8 +120,7 @@ class SFTP(FetchMethod):
 
         remote = '%s%s:%s' % (user, urlo.hostname, path)
 
-        cmd = '%s %s %s %s' % (basecmd, port, commands.mkarg(remote),
-                               commands.mkarg(lpath))
+        cmd = '%s %s %s %s' % (basecmd, port, remote, lpath)
 
         bb.fetch2.check_network_access(d, cmd, ud.url)
         runfetchcmd(cmd, d)
lib/bb/fetch2/ssh.py +2 -4
index 635578a..56f9b7e 100644
@@ -114,12 +114,10 @@ class SSH(FetchMethod):
             fr = host
         fr += ':%s' % path
 
-
-        import commands
         cmd = 'scp -B -r %s %s %s/' % (
             portarg,
-            commands.mkarg(fr),
-            commands.mkarg(dldir)
+            fr,
+            dldir
         )
 
         bb.fetch2.check_network_access(d, cmd, urldata.url)
lib/bb/fetch2/wget.py +24 -24

144 lines not on this page · raw message

lib/bb/main.py +6 -5
index 761ea45..b296ef8 100755
@@ -27,6 +27,7 @@ import sys
 import logging
 import optparse
 import warnings
+import fcntl
 
 import bb
 from bb import event
@@ -336,10 +337,7 @@ def start_server(servermodule, configParams, configuration, features):
         server.saveConnectionDetails()
     except Exception as e:
         while hasattr(server, "event_queue"):
-            try:
-                import queue
-            except ImportError:
-                import Queue as queue
+            import queue
             try:
                 event = server.event_queue.get(block=False)
             except (queue.Empty, IOError):
@@ -363,7 +361,10 @@ def bitbake_main(configParams, configuration):
     # updates to log files for use with tail
     try:
         if sys.stdout.name == '<stdout>':
-            sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
+            # Reopen with O_SYNC (unbuffered)
+            fl = fcntl.fcntl(sys.stdout.fileno(), fcntl.F_GETFL)
+            fl |= os.O_SYNC
+            fcntl.fcntl(sys.stdout.fileno(), fcntl.F_SETFL, fl)
     except:
         pass
 
lib/bb/msg.py +1 -1
index 6fdd1f5..8c3ab47 100644
@@ -57,7 +57,7 @@ class BBLogFormatter(logging.Formatter):
     }
 
     color_enabled = False
-    BASECOLOR, BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(29,38)
+    BASECOLOR, BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = list(range(29,38))
 
     COLORS = {
         DEBUG3  : CYAN,
lib/bb/parse/ast.py +9 -9
index bc3a2f8..548929f 100644
@@ -138,7 +138,7 @@ class DataNode(AstNode):
             data.setVar(key, val, parsing=True, **loginfo)
 
 class MethodNode(AstNode):
-    tr_tbl = string.maketrans('/.+-@%&', '_______')
+    tr_tbl = str.maketrans('/.+-@%&', '_______')
 
     def __init__(self, filename, lineno, func_name, body, python, fakeroot):
         AstNode.__init__(self, filename, lineno)
@@ -340,17 +340,17 @@ def _create_variants(datastores, names, function, onlyfinalise):
         function(arg or name, new_d)
         datastores[name] = new_d
 
-    for variant, variant_d in datastores.items():
+    for variant in list(datastores.keys()):
         for name in names:
             if not variant:
                 # Based on main recipe
-                create_variant(name, variant_d)
+                create_variant(name, datastores[""])
             else:
-                create_variant("%s-%s" % (variant, name), variant_d, name)
+                create_variant("%s-%s" % (variant, name), datastores[variant], name)
 
 def _expand_versions(versions):
     def expand_one(version, start, end):
-        for i in xrange(start, end + 1):
+        for i in range(start, end + 1):
             ver = _bbversions_re.sub(str(i), version, 1)
             yield ver
 
@@ -459,16 +459,16 @@ def multi_finalize(fn, d):
         safe_d.setVar("BBCLASSEXTEND", extended)
         _create_variants(datastores, extendedmap.keys(), extendfunc, onlyfinalise)
 
-    for variant, variant_d in datastores.iteritems():
+    for variant in datastores.keys():
         if variant:
             try:
                 if not onlyfinalise or variant in onlyfinalise:
-                    finalize(fn, variant_d, variant)
+                    finalize(fn, datastores[variant], variant)
             except bb.parse.SkipRecipe as e:
-                variant_d.setVar("__SKIPPED", e.args[0])
+                datastores[variant].setVar("__SKIPPED", e.args[0])
 
     if len(datastores) > 1:
-        variants = filter(None, datastores.iterkeys())
+        variants = filter(None, datastores.keys())
         safe_d.setVar("__VARIANTS", " ".join(variants))
 
     datastores[""] = d
lib/bb/persist_data.py +5 -5
index e450423..403f3a5 100644
@@ -92,9 +92,9 @@ class SQLTable(collections.MutableMapping):
         self._execute("DELETE from %s where key=?;" % self.table, [key])
 
     def __setitem__(self, key, value):
-        if not isinstance(key, basestring):
+        if not isinstance(key, str):
             raise TypeError('Only string keys are supported')
-        elif not isinstance(value, basestring):
+        elif not isinstance(value, str):
             raise TypeError('Only string values are supported')
 
         data = self._execute("SELECT * from %s where key=?;" %
@@ -131,14 +131,14 @@ class SQLTable(collections.MutableMapping):
         return [row[1] for row in data]
 
     def values(self):
-        return list(self.itervalues())
+        return list(self.values())
 
     def itervalues(self):
         data = self._execute("SELECT value FROM %s;" % self.table)
         return (row[0] for row in data)
 
     def items(self):
-        return list(self.iteritems())
+        return list(self.items())
 
     def iteritems(self):
         return self._execute("SELECT * FROM %s;" % self.table)
@@ -178,7 +178,7 @@ class PersistData(object):
         """
         Return a list of key + value pairs for a domain
         """
-        return self.data[domain].items()
+        return list(self.data[domain].items())
 
     def getValue(self, domain, key):
         """
lib/bb/process.py +26 -10
index 1c07f2d..c62d7bc 100644
@@ -17,7 +17,7 @@ class CmdError(RuntimeError):
         self.msg = msg
 
     def __str__(self):
-        if not isinstance(self.command, basestring):
+        if not isinstance(self.command, str):
             cmd = subprocess.list2cmdline(self.command)
         else:
             cmd = self.command
@@ -97,6 +97,8 @@ def _logged_communicate(pipe, log, input, extrafiles):
     try:
         while pipe.poll() is None:
             rlist = rin
+            stdoutbuf = b""
+            stderrbuf = b""
             try:
                 r,w,e = select.select (rlist, [], [], 1)
             except OSError as e:
@@ -104,16 +106,26 @@ def _logged_communicate(pipe, log, input, extrafiles):
                     raise
 
             if pipe.stdout in r:
-                data = pipe.stdout.read()
-                if data is not None:
-                    outdata.append(data)
-                    log.write(data)
+                data = stdoutbuf + pipe.stdout.read()
+                if data is not None and len(data) > 0:
+                    try:
+                        data = data.decode("utf-8")
+                        outdata.append(data)
+                        log.write(data)
+                        stdoutbuf = b""
+                    except UnicodeDecodeError:
+                        stdoutbuf = data
 
             if pipe.stderr in r:
-                data = pipe.stderr.read()
-                if data is not None:
-                    errdata.append(data)
-                    log.write(data)
+                data = stderrbuf + pipe.stderr.read()
+                if data is not None and len(data) > 0:
+                    try:
+                        data = data.decode("utf-8")
+                        errdata.append(data)
+                        log.write(data)
+                        stderrbuf = b""
+                    except UnicodeDecodeError:
+                        stderrbuf = data
 
             readextras(r)
 
@@ -135,7 +147,7 @@ def run(cmd, input=None, log=None, extrafiles=None, **options):
     if not extrafiles:
         extrafiles = []
 
-    if isinstance(cmd, basestring) and not "shell" in options:
+    if isinstance(cmd, str) and not "shell" in options:
         options["shell"] = True
 
     try:
@@ -150,6 +162,10 @@ def run(cmd, input=None, log=None, extrafiles=None, **options):
         stdout, stderr = _logged_communicate(pipe, log, input, extrafiles)
     else:
         stdout, stderr = pipe.communicate(input)
+        if stdout:
+            stdout = stdout.decode("utf-8")
+        if stderr:
+            stderr = stderr.decode("utf-8")
 
     if pipe.returncode != 0:
         raise ExecutionError(cmd, pipe.returncode, stdout, stderr)
lib/bb/providers.py +1 -1
index 563a091..80701b2 100644
@@ -245,7 +245,7 @@ def _filterProviders(providers, item, cfgData, dataCache):
             pkg_pn[pn] = []
         pkg_pn[pn].append(p)
 
-    logger.debug(1, "providers for %s are: %s", item, pkg_pn.keys())
+    logger.debug(1, "providers for %s are: %s", item, list(pkg_pn.keys()))
 
     # First add PREFERRED_VERSIONS
     for pn in pkg_pn:
lib/bb/pysh/builtin.py +1 -1
index b748e4a..a8814dc 100644
@@ -527,7 +527,7 @@ def utility_sed(name, args, interp, env, stdin, stdout, stderr, debugflags):
         print interp.log(' '.join([name, str(args), interp['PWD']]) + '\n')
         
     # Scan pattern arguments and append a space if necessary
-    for i in xrange(len(args)):
+    for i in range(len(args)):
         if not RE_SED.search(args[i]):
             continue
         args[i] = args[i] + ' '
lib/bb/pysh/interp.py +2 -2
index 25d8c92..d14ecf3 100644
@@ -474,7 +474,7 @@ class Environment:
         """
         # Save and remove previous arguments
         prevargs = []        
-        for i in xrange(int(self._env['#'])):
+        for i in range(int(self._env['#'])):
             i = str(i+1)
             prevargs.append(self._env[i])
             del self._env[i]
@@ -488,7 +488,7 @@ class Environment:
         return prevargs
         
     def get_positional_args(self):
-        return [self._env[str(i+1)] for i in xrange(int(self._env['#']))]
+        return [self._env[str(i+1)] for i in range(int(self._env['#']))]
         
     def get_variables(self):
         return dict(self._env)
lib/bb/pysh/pyshlex.py +1 -1
index b301236..fbf094b 100644
@@ -20,7 +20,7 @@ except NameError:
     from Set import Set as set
 
 from ply import lex
-from sherrors import *
+from bb.pysh.sherrors import *
 
 class NeedMore(Exception):
     pass
lib/bb/pysh/pyshyacc.py +2 -2
index e8e80aa..ba4cefd 100644
@@ -10,11 +10,11 @@
 import os.path
 import sys
 
-import pyshlex
+import bb.pysh.pyshlex as pyshlex
 tokens = pyshlex.tokens
 
 from ply import yacc
-import sherrors
+import bb.pysh.sherrors as sherrors
     
 class IORedirect:
     def __init__(self, op, filename, io_number=None):
lib/bb/runqueue.py +56 -61

407 lines not on this page · raw message

lib/bb/server/process.py +4 -4
index cc58c72..982fcf7 100644
@@ -30,7 +30,7 @@ import signal
 import sys
 import time
 import select
-from Queue import Empty
+from queue import Empty
 from multiprocessing import Event, Process, util, Queue, Pipe, queues, Manager
 
 from . import BitBakeBaseServer, BitBakeBaseServerConnection, BaseImplServer
@@ -137,7 +137,7 @@ class ProcessServer(Process, BaseImplServer):
         if not fds:
             fds = []
 
-        for function, data in self._idlefuns.items():
+        for function, data in list(self._idlefuns.items()):
             try:
                 retval = function(self, data, False)
                 if retval is False:
@@ -145,7 +145,7 @@ class ProcessServer(Process, BaseImplServer):
                     nextsleep = None
                 elif retval is True:
                     nextsleep = None
-                elif isinstance(retval, float):
+                elif isinstance(retval, float) and nextsleep:
                     if (retval < nextsleep):
                         nextsleep = retval
                 elif nextsleep is None:
@@ -213,7 +213,7 @@ class BitBakeProcessServerConnection(BitBakeBaseServerConnection):
 # Wrap Queue to provide API which isn't server implementation specific
 class ProcessEventQueue(multiprocessing.queues.Queue):
     def __init__(self, maxsize):
-        multiprocessing.queues.Queue.__init__(self, maxsize)
+        multiprocessing.queues.Queue.__init__(self, maxsize, ctx=multiprocessing.get_context())
         self.exit = False
         bb.utils.set_process_name("ProcessEQueue")
 
lib/bb/server/xmlrpc.py +25 -23

102 lines not on this page · raw message

lib/bb/siggen.py +7 -12
index e4085cf..db3daef 100644
@@ -3,19 +3,14 @@ import logging
 import os
 import re
 import tempfile
+import pickle
 import bb.data
 from bb.checksum import FileChecksumCache
 
 logger = logging.getLogger('BitBake.SigGen')
 
-try:
-    import cPickle as pickle
-except ImportError:
-    import pickle
-    logger.info('Importing cPickle failed.  Falling back to a very slow implementation.')
-
 def init(d):
-    siggens = [obj for obj in globals().itervalues()
+    siggens = [obj for obj in globals().values()
                       if type(obj) is type and issubclass(obj, SignatureGenerator)]
 
     desired = d.getVar("BB_SIGNATURE_HANDLER", True) or "noop"
@@ -138,7 +133,7 @@ class SignatureGeneratorBasic(SignatureGenerator):
                 var = lookupcache[dep]
                 if var is not None:
                     data = data + str(var)
-            self.basehash[fn + "." + task] = hashlib.md5(data).hexdigest()
+            self.basehash[fn + "." + task] = hashlib.md5(data.encode("utf-8")).hexdigest()
             taskdeps[task] = alldeps
 
         self.taskdeps[fn] = taskdeps
@@ -223,7 +218,7 @@ class SignatureGeneratorBasic(SignatureGenerator):
             self.taints[k] = taint
             logger.warning("%s is tainted from a forced run" % k)
 
-        h = hashlib.md5(data).hexdigest()
+        h = hashlib.md5(data.encode("utf-8")).hexdigest()
         self.taskhash[k] = h
         #d.setVar("BB_TASKHASH_task-%s" % task, taskhash[task])
         return h
@@ -287,7 +282,7 @@ class SignatureGeneratorBasic(SignatureGenerator):
             with os.fdopen(fd, "wb") as stream:
                 p = pickle.dump(data, stream, -1)
                 stream.flush()
-            os.chmod(tmpfile, 0664)
+            os.chmod(tmpfile, 0o664)
             os.rename(tmpfile, sigfile)
         except (OSError, IOError) as err:
             try:
@@ -545,7 +540,7 @@ def calc_basehash(sigdata):
         if val is not None:
             basedata = basedata + str(val)
 
-    return hashlib.md5(basedata).hexdigest()
+    return hashlib.md5(basedata.encode("utf-8")).hexdigest()
 
 def calc_taskhash(sigdata):
     data = sigdata['basehash']
@@ -562,7 +557,7 @@ def calc_taskhash(sigdata):
         else:
             data = data + sigdata['taint']
 
-    return hashlib.md5(data).hexdigest()
+    return hashlib.md5(data.encode("utf-8")).hexdigest()
 
 
 def dump_sigfile(a):
lib/bb/taskdata.py +6 -6
index 9ae52d7..65628c8 100644
@@ -446,7 +446,7 @@ class TaskData:
             return
 
         if not item in dataCache.providers:
-            close_matches = self.get_close_matches(item, dataCache.providers.keys())
+            close_matches = self.get_close_matches(item, list(dataCache.providers.keys()))
             # Is it in RuntimeProviders ?
             all_p = bb.providers.getRuntimeProviders(dataCache, item)
             for fn in all_p:
@@ -576,7 +576,7 @@ class TaskData:
         dependees = self.get_dependees(targetid)
         for fnid in dependees:
             self.fail_fnid(fnid, missing_list)
-        for taskid in xrange(len(self.tasks_idepends)):
+        for taskid in range(len(self.tasks_idepends)):
             idepends = self.tasks_idepends[taskid]
             for (idependid, idependtask) in idepends:
                 if idependid == targetid:
@@ -602,7 +602,7 @@ class TaskData:
         dependees = self.get_rdependees(targetid)
         for fnid in dependees:
             self.fail_fnid(fnid, missing_list)
-        for taskid in xrange(len(self.tasks_irdepends)):
+        for taskid in range(len(self.tasks_irdepends)):
             irdepends = self.tasks_irdepends[taskid]
             for (idependid, idependtask) in irdepends:
                 if idependid == targetid:
@@ -658,7 +658,7 @@ class TaskData:
         logger.debug(3, ", ".join(self.run_names_index))
 
         logger.debug(3, "build_targets:")
-        for buildid in xrange(len(self.build_names_index)):
+        for buildid in range(len(self.build_names_index)):
             target = self.build_names_index[buildid]
             targets = "None"
             if buildid in self.build_targets:
@@ -666,7 +666,7 @@ class TaskData:
             logger.debug(3, " (%s)%s: %s", buildid, target, targets)
 
         logger.debug(3, "run_targets:")
-        for runid in xrange(len(self.run_names_index)):
+        for runid in range(len(self.run_names_index)):
             target = self.run_names_index[runid]
             targets = "None"
             if runid in self.run_targets:
@@ -674,7 +674,7 @@ class TaskData:
             logger.debug(3, " (%s)%s: %s", runid, target, targets)
 
         logger.debug(3, "tasks:")
-        for task in xrange(len(self.tasks_name)):
+        for task in range(len(self.tasks_name)):
             logger.debug(3, " (%s)%s - %s: %s",
                        task,
                        self.fn_index[self.tasks_fnid[task]],
lib/bb/tests/codeparser.py +2 -2
index 5ea9d84..14f0e25 100644
@@ -191,8 +191,8 @@ class PythonReferenceTest(ReferenceTest):
         if hasattr(bb.utils, "_context"):
             self.context = bb.utils._context
         else:
-            import __builtin__
-            self.context = __builtin__.__dict__
+            import builtins
+            self.context = builtins.__dict__
 
     def parseExpression(self, exp):
         parsedvar = self.d.expandWithRefs(exp, None)
lib/bb/tests/data.py +6 -6
index 1223230..b54eb06 100644
@@ -147,14 +147,14 @@ class DataExpansions(unittest.TestCase):
         self.assertEqual(self.d.getVar("foo", False), None)
 
     def test_keys(self):
-        keys = self.d.keys()
-        self.assertEqual(keys, ['value_of_foo', 'foo', 'bar'])
+        keys = list(self.d.keys())
+        self.assertCountEqual(keys, ['value_of_foo', 'foo', 'bar'])
 
     def test_keys_deletion(self):
         newd = bb.data.createCopy(self.d)
         newd.delVar("bar")
-        keys = newd.keys()
-        self.assertEqual(keys, ['value_of_foo', 'foo'])
+        keys = list(newd.keys())
+        self.assertCountEqual(keys, ['value_of_foo', 'foo'])
 
 class TestNestedExpansions(unittest.TestCase):
     def setUp(self):
@@ -334,7 +334,7 @@ class TestOverrides(unittest.TestCase):
         self.d.setVar("TEST2_bar", "testvalue2")
         bb.data.update_data(self.d)
         self.assertEqual(self.d.getVar("TEST2", True), "testvalue2")
-        self.assertItemsEqual(self.d.keys(), ['TEST', 'TEST2', 'OVERRIDES', 'TEST2_bar'])
+        self.assertCountEqual(list(self.d.keys()), ['TEST', 'TEST2', 'OVERRIDES', 'TEST2_bar'])
 
     def test_multiple_override(self):
         self.d.setVar("TEST_bar", "testvalue2")
@@ -342,7 +342,7 @@ class TestOverrides(unittest.TestCase):
         self.d.setVar("TEST_foo", "testvalue4")
         bb.data.update_data(self.d)
         self.assertEqual(self.d.getVar("TEST", True), "testvalue3")
-        self.assertItemsEqual(self.d.keys(), ['TEST', 'TEST_foo', 'OVERRIDES', 'TEST_bar', 'TEST_local'])
+        self.assertCountEqual(list(self.d.keys()), ['TEST', 'TEST_foo', 'OVERRIDES', 'TEST_bar', 'TEST_local'])
 
     def test_multiple_combined_overrides(self):
         self.d.setVar("TEST_local_foo_bar", "testvalue3")
lib/bb/tests/parse.py +1 -1
index 6beb76a..c296db2 100644
@@ -50,7 +50,7 @@ C = "3"
     def parsehelper(self, content, suffix = ".bb"):
 
         f = tempfile.NamedTemporaryFile(suffix = suffix)
-        f.write(content)
+        f.write(bytes(content, "utf-8"))
         f.flush()
         os.chdir(os.path.dirname(f.name))
         return f
lib/bb/ui/crumbs/hobwidget.py +1 -1
index 2b969c1..1f51a3c 100644
@@ -612,7 +612,7 @@ class HobIconChecker(hic):
     def set_hob_icon_to_stock_icon(self, file_path, stock_id=""):
         try:
             pixbuf = gtk.gdk.pixbuf_new_from_file(file_path)
-        except Exception, e:
+        except Exception as e:
             return None
 
         if stock_id and (gtk.icon_factory_lookup_default(stock_id) == None):
lib/bb/ui/crumbs/progressbar.py +3 -3
index 3e2c660..03230ae 100644
@@ -44,9 +44,9 @@ class HobProgressBar (gtk.ProgressBar):
         self.set_text(text)
 
     def set_stop_title(self, text=None):
-	if not text:
-	    text = ""
-	self.set_text(text)
+        if not text:
+            text = ""
+        self.set_text(text)
 
     def reset(self):
         self.set_fraction(0)
lib/bb/ui/crumbs/runningbuild.py +6 -6
index 16a955d..9b695ac 100644
@@ -23,14 +23,14 @@ import gtk
 import gobject
 import logging
 import time
-import urllib
-import urllib2
+import urllib.request, urllib.parse, urllib.error
+import urllib.request, urllib.error, urllib.parse
 import pango
 from bb.ui.crumbs.hobcolor import HobColors
 from bb.ui.crumbs.hobwidget import HobWarpCellRendererText, HobCellRendererPixbuf
 
 class RunningBuildModel (gtk.TreeStore):
-    (COL_LOG, COL_PACKAGE, COL_TASK, COL_MESSAGE, COL_ICON, COL_COLOR, COL_NUM_ACTIVE) = range(7)
+    (COL_LOG, COL_PACKAGE, COL_TASK, COL_MESSAGE, COL_ICON, COL_COLOR, COL_NUM_ACTIVE) = list(range(7))
 
     def __init__ (self):
         gtk.TreeStore.__init__ (self,
@@ -443,8 +443,8 @@ def do_pastebin(text):
     url = 'http://pastebin.com/api_public.php'
     params = {'paste_code': text, 'paste_format': 'text'}
 
-    req = urllib2.Request(url, urllib.urlencode(params))
-    response = urllib2.urlopen(req)
+    req = urllib.request.Request(url, urllib.parse.urlencode(params))
+    response = urllib.request.urlopen(req)
     paste_url = response.read()
 
     return paste_url
@@ -519,7 +519,7 @@ class RunningBuildTreeView (gtk.TreeView):
 
         # @todo Provide visual feedback to the user that it is done and that
         # it worked.
-        print paste_url
+        print(paste_url)
 
         self._add_to_clipboard(paste_url)
 
lib/bb/ui/goggle.py +8 -3
index f4ee7b4..f5f8f16 100644
@@ -18,13 +18,18 @@
 # with this program; if not, write to the Free Software Foundation, Inc.,
 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
+from gi import pygtkcompat
+
+pygtkcompat.enable()
+pygtkcompat.enable_gtk(version='3.0')
+
 import gobject
 import gtk
-import xmlrpclib
+import xmlrpc.client
 from bb.ui.crumbs.runningbuild import RunningBuildTreeView, RunningBuild
 from bb.ui.crumbs.progress import ProgressBar
 
-import Queue
+import queue
 
 
 def event_handle_idle_func (eventHandler, build, pbar):
@@ -96,7 +101,7 @@ def main (server, eventHandler, params):
         elif ret != True:
             print("Error running command '%s': returned %s" % (cmdline, ret))
             return 1
-    except xmlrpclib.Fault as x:
+    except xmlrpcclient.Fault as x:
         print("XMLRPC Fault getting commandline:\n %s" % x)
         return 1
 
lib/bb/ui/knotty.py +3 -3
index 08c872e..9605c8e 100644
@@ -22,7 +22,7 @@ from __future__ import division
 
 import os
 import sys
-import xmlrpclib
+import xmlrpc.client as xmlrpclib
 import logging
 import progressbar
 import signal
@@ -184,8 +184,8 @@ class TerminalFilter(object):
     def clearFooter(self):
         if self.footer_present:
             lines = self.footer_present
-            sys.stdout.write(self.curses.tparm(self.cuu, lines))
-            sys.stdout.write(self.curses.tparm(self.ed))
+            sys.stdout.buffer.write(self.curses.tparm(self.cuu, lines))
+            sys.stdout.buffer.write(self.curses.tparm(self.ed))
             sys.stdout.flush()
         self.footer_present = False
 
lib/bb/ui/ncurses.py +4 -4
index 9589a77..d81e413 100644
@@ -45,7 +45,7 @@
 """
 
 
-from __future__ import division
+
 import logging
 import os, sys, itertools, time, subprocess
 
@@ -55,7 +55,7 @@ except ImportError:
     sys.exit("FATAL: The ncurses ui could not load the required curses python module.")
 
 import bb
-import xmlrpclib
+import xmlrpc.client
 from bb import ui
 from bb.ui import uihelper
 
@@ -252,7 +252,7 @@ class NCursesUI:
             elif ret != True:
                 print("Couldn't get default commandlind! %s" % ret)
                 return
-        except xmlrpclib.Fault as x:
+        except xmlrpc.client.Fault as x:
             print("XMLRPC Fault getting commandline:\n %s" % x)
             return
 
@@ -331,7 +331,7 @@ class NCursesUI:
                     taw.setText(0, 0, "")
                     if activetasks:
                         taw.appendText("Active Tasks:\n")
-                        for task in activetasks.itervalues():
+                        for task in activetasks.values():
                             taw.appendText(task["title"] + '\n')
                     if failedtasks:
                         taw.appendText("Failed Tasks:\n")
lib/bb/ui/uievent.py +2 -2
index df093c5..ca19166 100644
@@ -25,7 +25,7 @@ client/server deadlocks.
 """
 
 import socket, threading, pickle, collections
-from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
+from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
 
 class BBUIEventQueue:
     def __init__(self, BBServer, clientinfo=("localhost, 0")):
@@ -137,7 +137,7 @@ class UIXMLRPCServer (SimpleXMLRPCServer):
         SimpleXMLRPCServer.__init__( self,
                                     interface,
                                     requestHandler=SimpleXMLRPCRequestHandler,
-                                    logRequests=False, allow_none=True)
+                                    logRequests=False, allow_none=True, use_builtin_types=True)
 
     def get_request(self):
         while not self.quit:
lib/bb/utils.py +10 -10
index 588c192..138da44 100644
@@ -37,7 +37,7 @@ import errno
 import signal
 import ast
 import collections
-from commands import getstatusoutput
+from subprocess import getstatusoutput
 from contextlib import contextmanager
 from ctypes import cdll
 
@@ -76,7 +76,7 @@ def explode_version(s):
             r.append((0, int(m.group(1))))
             s = m.group(2)
             continue
-        if s[0] in string.letters:
+        if s[0] in string.ascii_letters:
             m = alpha_regexp.match(s)
             r.append((1, m.group(1)))
             s = m.group(2)
@@ -588,7 +588,7 @@ def filter_environment(good_vars):
     """
 
     removed_vars = {}
-    for key in os.environ.keys():
+    for key in list(os.environ):
         if key in good_vars:
             continue
 
@@ -641,7 +641,7 @@ def empty_environment():
     """
     Remove all variables from the environment.
     """
-    for s in os.environ.keys():
+    for s in list(os.environ.keys()):
         os.unsetenv(s)
         del os.environ[s]
 
@@ -958,7 +958,7 @@ def contains(variable, checkvalues, truevalue, falsevalue, d):
     if not val:
         return falsevalue
     val = set(val.split())
-    if isinstance(checkvalues, basestring):
+    if isinstance(checkvalues, str):
         checkvalues = set(checkvalues.split())
     else:
         checkvalues = set(checkvalues)
@@ -971,7 +971,7 @@ def contains_any(variable, checkvalues, truevalue, falsevalue, d):
     if not val:
         return falsevalue
     val = set(val.split())
-    if isinstance(checkvalues, basestring):
+    if isinstance(checkvalues, str):
         checkvalues = set(checkvalues.split())
     else:
         checkvalues = set(checkvalues)
@@ -1040,7 +1040,7 @@ def exec_flat_python_func(func, *args, **kwargs):
         aidx += 1
     # Handle keyword arguments
     context.update(kwargs)
-    funcargs.extend(['%s=%s' % (arg, arg) for arg in kwargs.iterkeys()])
+    funcargs.extend(['%s=%s' % (arg, arg) for arg in kwargs.keys()])
     code = 'retval = %s(%s)' % (func, ', '.join(funcargs))
     comp = bb.utils.better_compile(code, '<string>', '<string>')
     bb.utils.better_exec(comp, context, code, '<string>')
@@ -1127,7 +1127,7 @@ def edit_metadata(meta_lines, variables, varfunc, match_overrides=False):
             else:
                 varset_new = varset_start
 
-            if isinstance(indent, (int, long)):
+            if isinstance(indent, int):
                 if indent == -1:
                     indentspc = ' ' * (len(varset_new) + 2)
                 else:
@@ -1195,7 +1195,7 @@ def edit_metadata(meta_lines, variables, varfunc, match_overrides=False):
                 in_var = None
         else:
             skip = False
-            for (varname, var_re) in var_res.iteritems():
+            for (varname, var_re) in var_res.items():
                 res = var_re.match(line)
                 if res:
                     isfunc = varname.endswith('()')
@@ -1373,7 +1373,7 @@ def get_file_layer(filename, d):
         # Use longest path so we handle nested layers
         matchlen = 0
         match = None
-        for collection, regex in collection_res.iteritems():
+        for collection, regex in collection_res.items():
             if len(regex) > matchlen and re.match(regex, path):
                 matchlen = len(regex)
                 match = collection
lib/bblayers/action.py +1 -1
index 5b95e2e..d4c1792 100644
@@ -117,7 +117,7 @@ build results (as the layer priority order has effectively changed).
         applied_appends = []
         for layer in layers:
             overlayed = []
-            for f in self.tinfoil.cooker.collection.overlayed.iterkeys():
+            for f in self.tinfoil.cooker.collection.overlayed.keys():
                 for of in self.tinfoil.cooker.collection.overlayed[f]:
                     if of.startswith(layer):
                         overlayed.append(of)
lib/bblayers/common.py +1 -1
index 360b9d7..b10fb4c 100644
@@ -14,7 +14,7 @@ class LayerPlugin():
         self.tinfoil = tinfoil
         self.bblayers = (self.tinfoil.config_data.getVar('BBLAYERS', True) or "").split()
         layerconfs = self.tinfoil.config_data.varhistory.get_variable_items_files('BBFILE_COLLECTIONS', self.tinfoil.config_data)
-        self.bbfile_collections = {layer: os.path.dirname(os.path.dirname(path)) for layer, path in layerconfs.iteritems()}
+        self.bbfile_collections = {layer: os.path.dirname(os.path.dirname(path)) for layer, path in layerconfs.items()}
 
     @staticmethod
     def add_command(subparsers, cmdname, function, parserecipes=True, *args, **kwargs):
lib/bblayers/layerindex.py +6 -6
index 3c39d8a..10ad718 100644
@@ -1,10 +1,10 @@
 import argparse
-import httplib
+import http.client
 import json
 import logging
 import os
 import subprocess
-import urlparse
+import urllib.parse
 
 from bblayers.action import ActionPlugin
 
@@ -24,12 +24,12 @@ class LayerIndexPlugin(ActionPlugin):
     def get_json_data(self, apiurl):
         proxy_settings = os.environ.get("http_proxy", None)
         conn = None
-        _parsedurl = urlparse.urlparse(apiurl)
+        _parsedurl = urllib.parse.urlparse(apiurl)
         path = _parsedurl.path
         query = _parsedurl.query
 
         def parse_url(url):
-            parsedurl = urlparse.urlparse(url)
+            parsedurl = urllib.parse.urlparse(url)
             if parsedurl.netloc[0] == '[':
                 host, port = parsedurl.netloc[1:].split(']', 1)
                 if ':' in port:
@@ -46,11 +46,11 @@ class LayerIndexPlugin(ActionPlugin):
 
         if proxy_settings is None:
             host, port = parse_url(apiurl)
-            conn = httplib.HTTPConnection(host, port)
+            conn = http.client.HTTPConnection(host, port)
             conn.request("GET", path + "?" + query)
         else:
             host, port = parse_url(proxy_settings)
-            conn = httplib.HTTPConnection(host, port)
+            conn = http.client.HTTPConnection(host, port)
             conn.request("GET", apiurl)
 
         r = conn.getresponse()
lib/bblayers/query.py +2 -2
index b5b98f7..b8c817b 100644
@@ -128,7 +128,7 @@ skipped recipes will also be listed, with a " (skipped)" suffix.
         # Ensure we list skipped recipes
         # We are largely guessing about PN, PV and the preferred version here,
         # but we have no choice since skipped recipes are not fully parsed
-        skiplist = self.tinfoil.cooker.skiplist.keys()
+        skiplist = list(self.tinfoil.cooker.skiplist.keys())
         skiplist.sort( key=lambda fileitem: self.tinfoil.cooker.collection.calc_bbfile_priority(fileitem) )
         skiplist.reverse()
         for fn in skiplist:
@@ -275,7 +275,7 @@ Lists recipes with the bbappends that apply to them as subitems.
 
     def show_appends_for_skipped(self):
         filenames = [os.path.basename(f)
-                    for f in self.tinfoil.cooker.skiplist.iterkeys()]
+                    for f in self.tinfoil.cooker.skiplist.keys()]
         return self.show_appends_output(filenames, None, " (skipped)")
 
     def show_appends_output(self, filenames, best_filename, name_suffix = ''):
lib/codegen.py +4 -4
index be772d5..62a6748 100644
@@ -214,11 +214,11 @@ class SourceGenerator(NodeVisitor):
                 paren_or_comma()
                 self.write(keyword.arg + '=')
                 self.visit(keyword.value)
-            if node.starargs is not None:
+            if hasattr(node, 'starargs') and node.starargs is not None:
                 paren_or_comma()
                 self.write('*')
                 self.visit(node.starargs)
-            if node.kwargs is not None:
+            if hasattr(node, 'kwargs') and node.kwargs is not None:
                 paren_or_comma()
                 self.write('**')
                 self.visit(node.kwargs)
@@ -379,11 +379,11 @@ class SourceGenerator(NodeVisitor):
             write_comma()
             self.write(keyword.arg + '=')
             self.visit(keyword.value)
-        if node.starargs is not None:
+        if hasattr(node, 'starargs') and node.starargs is not None:
             write_comma()
             self.write('*')
             self.visit(node.starargs)
-        if node.kwargs is not None:
+        if hasattr(node, 'kwargs') and node.kwargs is not None:
             write_comma()
             self.write('**')
             self.visit(node.kwargs)
lib/ply/yacc.py +2 -0
index 6168fd9..d50886e 100644
@@ -195,6 +195,8 @@ class YaccProduction:
         self.lexer = None
         self.parser= None
     def __getitem__(self,n):
+        if isinstance(n,slice):
+            return [self[i] for i in range(*(n.indices(len(self.slice))))]
         if n >= 0: return self.slice[n].value
         else: return self.stack[n].value
 
lib/prserv/db.py +1 -1
index 2a86184..495d09f 100644
@@ -260,7 +260,7 @@ class PRData(object):
         self.connection.close()
 
     def __getitem__(self,tblname):
-        if not isinstance(tblname, basestring):
+        if not isinstance(tblname, str):
             raise TypeError("tblname argument must be a string, not '%s'" %
                             type(tblname))
         if tblname in self._tables:
lib/prserv/serv.py +7 -7
index 8cec9f8..cafcc82 100644
@@ -1,10 +1,10 @@
 import os,sys,logging
 import signal, time
-from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
+from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
 import threading
-import Queue
+import queue
 import socket
-import StringIO
+import io
 
 try:
     import sqlite3
@@ -64,7 +64,7 @@ class PRServer(SimpleXMLRPCServer):
         self.register_function(self.importone, "importone")
         self.register_introspection_functions()
 
-        self.requestqueue = Queue.Queue()
+        self.requestqueue = queue.Queue()
         self.handlerthread = threading.Thread(target = self.process_request_thread)
         self.handlerthread.daemon = False
 
@@ -83,7 +83,7 @@ class PRServer(SimpleXMLRPCServer):
         while not self.quit:
             try:
                 (request, client_address) = self.requestqueue.get(True, 30)
-            except Queue.Empty:
+            except queue.Empty:
                 self.table.sync_if_dirty()
                 continue
             try:
@@ -126,7 +126,7 @@ class PRServer(SimpleXMLRPCServer):
         Returns None if the database engine does not support dumping to
         script or if some other error is encountered in processing.
         """
-        buff = StringIO.StringIO()
+        buff = io.StringIO()
         try:
             self.table.sync()
             self.table.dump_db(buff)
@@ -420,7 +420,7 @@ class PRServiceConfigError(Exception):
 def auto_start(d):
     global singleton
 
-    host_params = filter(None, (d.getVar('PRSERV_HOST', True) or '').split(':'))
+    host_params = list(filter(None, (d.getVar('PRSERV_HOST', True) or '').split(':')))
     if not host_params:
         return None
 
Signature · 1 line
2.5.0
#4 lore raw

PATCH 5/28 data_smart: Simplify ExpansionError exception

In reply to Richard Purdie

This seemingly convoluted syntax doesn't work in python3. Instead use the chained exception handling syntax which appears to make more sense here.

---
 lib/bb/data_smart.py | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
lib/bb/data_smart.py +1 -2
index 2a61386..25c412c 100644
@@ -397,8 +397,7 @@ class DataSmart(MutableMapping):
             except bb.parse.SkipRecipe:
                 raise
             except Exception as exc:
-                exc_class, exc, tb = sys.exc_info()
-                raise ExpansionError, ExpansionError(varname, s, exc), tb
+                raise ExpansionError(varname, s, exc) from exc
 
         varparse.value = s
 
Signature · 1 line
2.5.0
#5 lore raw

PATCH 6/28 lib/bb: Set required python 3 version to 3.4.0

In reply to Richard Purdie

From: Jeremy Puhlman <[email protected]>

get_context was added to mutliprocessing as part of 3.4.0

---
 lib/bb/__init__.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
lib/bb/__init__.py +2 -2
index 6b85984..a98ebd1 100644
@@ -24,8 +24,8 @@
 __version__ = "1.31.0"
 
 import sys
-if sys.version_info < (2, 7, 3):
-    raise RuntimeError("Sorry, python 2.7.3 or later is required for this version of bitbake")
+if sys.version_info < (3, 4, 0):
+    raise RuntimeError("Sorry, python 3.4.0 or later is required for this version of bitbake")
 
 
 class BBHandledException(Exception):
Signature · 1 line
2.5.0
#6 lore raw

PATCH 7/28 image-writer/goggle: Disable pygtkcompat problems

In reply to Richard Purdie

Disable the problematic gtk usage for use with pygtkcompat. The following commit removes these tools/UIs entirely but we may as well leave this piece in the history in case anyone does want a starting point for reusing them.

---
 bin/image-writer                     |  3 ++-
 lib/bb/ui/crumbs/hig/crumbsdialog.py |  2 +-
 lib/bb/ui/crumbs/hobwidget.py        |  8 ++++----
 lib/bb/ui/crumbs/progressbar.py      | 15 ++++++++-------
 4 files changed, 15 insertions(+), 13 deletions(-)
bin/image-writer +2 -1
index 7ab1d8c..40e284d 100755
@@ -67,7 +67,8 @@ class DeployWindow(gtk.Window):
 
         self.deploy_dialog = DeployImageDialog(Title, image_path, self,
                                         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT
-                                        | gtk.DIALOG_NO_SEPARATOR, None, standalone=True)
+                                        , None, standalone=True)
+#FIXME | gtk.DIALOG_NO_SEPARATOR
         close_button = self.deploy_dialog.add_button("Close", gtk.RESPONSE_NO)
         HobAltButton.style_button(close_button)
         close_button.connect('clicked', gtk.main_quit)
lib/bb/ui/crumbs/hig/crumbsdialog.py +1 -1
index c679f9a..73b9234 100644
@@ -36,7 +36,7 @@ class CrumbsDialog(gtk.Dialog):
     def __init__(self, title="", parent=None, flags=0, buttons=None):
         super(CrumbsDialog, self).__init__(title, parent, flags, buttons)
 
-        self.set_property("has-separator", False) # note: deprecated in 2.22
+        #FIXME self.set_property("has-separator", False) # note: deprecated in 2.22
 
         self.set_border_width(6)
         self.vbox.set_property("spacing", 12)
lib/bb/ui/crumbs/hobwidget.py +4 -4
index 1f51a3c..3f6138b 100644
@@ -273,13 +273,13 @@ class BaseHobButton(gtk.Button):
         style = button.get_style()
         style = gtk.rc_get_style_by_paths(gtk.settings_get_default(), 'gtk-button', 'gtk-button', gobject.TYPE_NONE)
 
-        button.set_flags(gtk.CAN_DEFAULT)
+        #FIXME button.set_flags(gtk.CAN_DEFAULT)
         button.grab_default()
 
 #        label = "<span size='x-large'><b>%s</b></span>" % gobject.markup_escape_text(button.get_label())
         label = button.get_label()
         button.set_label(label)
-        button.child.set_use_markup(True)
+        #FIXME button.child.set_use_markup(True)
 
 class HobButton(BaseHobButton):
     """
@@ -399,8 +399,8 @@ class HobInfoButton(gtk.EventBox):
         self.dialog = PropertyDialog(title = '',
                     parent = self.my_parent,
                     information = self.tip_markup,
-                    flags = gtk.DIALOG_DESTROY_WITH_PARENT
-                        | gtk.DIALOG_NO_SEPARATOR)
+                    flags = gtk.DIALOG_DESTROY_WITH_PARENT)
+                        #FMXIE | gtk.DIALOG_NO_SEPARATOR
 
         button = self.dialog.add_button("Close", gtk.RESPONSE_CANCEL)
         HobAltButton.style_button(button)
lib/bb/ui/crumbs/progressbar.py +8 -7
index 03230ae..ba3c7a0 100644
@@ -28,13 +28,14 @@ class HobProgressBar (gtk.ProgressBar):
 
     def set_rcstyle(self, status):
         rcstyle = gtk.RcStyle()
-        rcstyle.fg[2] = gtk.gdk.Color(HobColors.BLACK)
-        if status == "stop":
-            rcstyle.bg[3] = gtk.gdk.Color(HobColors.WARNING)
-        elif status == "fail":
-            rcstyle.bg[3] = gtk.gdk.Color(HobColors.ERROR)
-        else:
-            rcstyle.bg[3] = gtk.gdk.Color(HobColors.RUNNING)
+#FIXME
+#        rcstyle.fg[2] = gtk.gdk.Color(HobColors.BLACK)
+#        if status == "stop":
+#            rcstyle.bg[3] = gtk.gdk.Color(HobColors.WARNING)
+#        elif status == "fail":
+#            rcstyle.bg[3] = gtk.gdk.Color(HobColors.ERROR)
+#        else:
+#            rcstyle.bg[3] = gtk.gdk.Color(HobColors.RUNNING)
         self.modify_style(rcstyle)
 
     def set_title(self, text=None):
Signature · 1 line
2.5.0
#7 lore raw

PATCH 8/28 google/image-writer: Drop since bitrotting and no longer used

In reply to Richard Purdie

The upgrade to python3 is the final nail in the coffin for image-writer and the goggle UI. Neither seem used or recieve patches and are based on old versions of GTK+ so drop them, and the remaining crumbs support pieces.

---
 bin/image-writer                             | 127 ----
 lib/bb/ui/crumbs/__init__.py                 |  17 -
 lib/bb/ui/crumbs/hig/__init__.py             |   0
 lib/bb/ui/crumbs/hig/crumbsdialog.py         |  44 --
 lib/bb/ui/crumbs/hig/crumbsmessagedialog.py  |  70 ---
 lib/bb/ui/crumbs/hig/deployimagedialog.py    | 219 -------
 lib/bb/ui/crumbs/hig/imageselectiondialog.py | 172 -----
 lib/bb/ui/crumbs/hig/layerselectiondialog.py | 298 ---------
 lib/bb/ui/crumbs/hig/propertydialog.py       | 437 -------------
 lib/bb/ui/crumbs/hig/settingsuihelper.py     | 122 ----
 lib/bb/ui/crumbs/hobcolor.py                 |  38 --
 lib/bb/ui/crumbs/hobwidget.py                | 904 ---------------------------
 lib/bb/ui/crumbs/persistenttooltip.py        | 186 ------
 lib/bb/ui/crumbs/progress.py                 |  23 -
 lib/bb/ui/crumbs/progressbar.py              |  60 --
 lib/bb/ui/crumbs/puccho.glade                | 606 ------------------
 lib/bb/ui/crumbs/runningbuild.py             | 551 ----------------
 lib/bb/ui/crumbs/utils.py                    |  34 -
 lib/bb/ui/goggle.py                          | 126 ----
 19 files changed, 4034 deletions(-)
 delete mode 100755 bin/image-writer
 delete mode 100644 lib/bb/ui/crumbs/__init__.py
 delete mode 100644 lib/bb/ui/crumbs/hig/__init__.py
 delete mode 100644 lib/bb/ui/crumbs/hig/crumbsdialog.py
 delete mode 100644 lib/bb/ui/crumbs/hig/crumbsmessagedialog.py
 delete mode 100644 lib/bb/ui/crumbs/hig/deployimagedialog.py
 delete mode 100644 lib/bb/ui/crumbs/hig/imageselectiondialog.py
 delete mode 100644 lib/bb/ui/crumbs/hig/layerselectiondialog.py
 delete mode 100644 lib/bb/ui/crumbs/hig/propertydialog.py
 delete mode 100644 lib/bb/ui/crumbs/hig/settingsuihelper.py
 delete mode 100644 lib/bb/ui/crumbs/hobcolor.py
 delete mode 100644 lib/bb/ui/crumbs/hobwidget.py
 delete mode 100644 lib/bb/ui/crumbs/persistenttooltip.py
 delete mode 100644 lib/bb/ui/crumbs/progress.py
 delete mode 100644 lib/bb/ui/crumbs/progressbar.py
 delete mode 100644 lib/bb/ui/crumbs/puccho.glade
 delete mode 100644 lib/bb/ui/crumbs/runningbuild.py
 delete mode 100644 lib/bb/ui/crumbs/utils.py
 delete mode 100644 lib/bb/ui/goggle.py
bin/image-writer deleted +0 -127
deleted file mode 100755
index 40e284d..0000000
@@ -1,127 +0,0 @@
-#!/usr/bin/env python3
-
-# Copyright (c) 2012 Wind River Systems, Inc.
-#
-# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-import os
-import sys
-sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname( \
-                                    os.path.abspath(__file__))), 'lib'))
-try:
-    import bb
-except RuntimeError as exc:
-    sys.exit(str(exc))
-
-from gi import pygtkcompat
-
-pygtkcompat.enable()
-pygtkcompat.enable_gtk(version='3.0')
-
-import gtk
-import optparse
-
-from bb.ui.crumbs.hobwidget import HobAltButton, HobButton
-from bb.ui.crumbs.hig.crumbsmessagedialog import CrumbsMessageDialog
-from bb.ui.crumbs.hig.deployimagedialog import DeployImageDialog
-from bb.ui.crumbs.hig.imageselectiondialog import ImageSelectionDialog
-
-# I put all the fs bitbake supported here. Need more test.
-DEPLOYABLE_IMAGE_TYPES = ["jffs2", "cramfs", "ext2", "ext3", "ext4", "btrfs", "squashfs", "ubi", "vmdk"]
-Title = "USB Image Writer"
-
-class DeployWindow(gtk.Window):
-    def __init__(self, image_path=''):
-        super(DeployWindow, self).__init__()
-
-        if len(image_path) > 0:
-            valid = True
-            if not os.path.exists(image_path):
-                valid = False
-                lbl = "<b>Invalid image file path: %s.</b>\nPress <b>Select Image</b> to select an image." % image_path
-            else:
-                image_path = os.path.abspath(image_path)
-                extend_name = os.path.splitext(image_path)[1][1:]
-                if extend_name not in DEPLOYABLE_IMAGE_TYPES:
-                    valid = False
-                    lbl = "<b>Undeployable imge type: %s</b>\nPress <b>Select Image</b> to select an image." % extend_name
-
-            if not valid:
-                image_path = ''
-                crumbs_dialog = CrumbsMessageDialog(self, lbl, gtk.STOCK_DIALOG_INFO)
-                button = crumbs_dialog.add_button("Close", gtk.RESPONSE_OK)
-                HobButton.style_button(button)
-                crumbs_dialog.run()
-                crumbs_dialog.destroy()
-
-        self.deploy_dialog = DeployImageDialog(Title, image_path, self,
-                                        gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT
-                                        , None, standalone=True)
-#FIXME | gtk.DIALOG_NO_SEPARATOR
-        close_button = self.deploy_dialog.add_button("Close", gtk.RESPONSE_NO)
-        HobAltButton.style_button(close_button)
-        close_button.connect('clicked', gtk.main_quit)
-
-        write_button = self.deploy_dialog.add_button("Write USB image", gtk.RESPONSE_YES)
-        HobAltButton.style_button(write_button)
-
-        self.deploy_dialog.connect('select_image_clicked', self.select_image_clicked_cb)
-        self.deploy_dialog.connect('destroy', gtk.main_quit)
-        response = self.deploy_dialog.show()
-
-    def select_image_clicked_cb(self, dialog):
-        cwd = os.getcwd()
-        dialog = ImageSelectionDialog(cwd, DEPLOYABLE_IMAGE_TYPES, Title, self, gtk.FILE_CHOOSER_ACTION_SAVE )
-        button = dialog.add_button("Cancel", gtk.RESPONSE_NO)
-        HobAltButton.style_button(button)
-        button = dialog.add_button("Open", gtk.RESPONSE_YES)
-        HobAltButton.style_button(button)
-        response = dialog.run()
-
-        if response == gtk.RESPONSE_YES:
-            if not dialog.image_names:
-                lbl = "<b>No selections made</b>\nClicked the radio button to select a image."
-                crumbs_dialog = CrumbsMessageDialog(self, lbl, gtk.STOCK_DIALOG_INFO)
-                button = crumbs_dialog.add_button("Close", gtk.RESPONSE_OK)
-                HobButton.style_button(button)
-                crumbs_dialog.run()
-                crumbs_dialog.destroy()
-                dialog.destroy()
-                return
-
-            # get the full path of image
-            image_path = os.path.join(dialog.image_folder, dialog.image_names[0])
-            self.deploy_dialog.set_image_text_buffer(image_path)
-            self.deploy_dialog.set_image_path(image_path)
-
-        dialog.destroy()
-
-def main():
-    parser = optparse.OptionParser(
-                usage = """%prog [-h] [image_file]
-
-%prog writes bootable images to USB devices. You can
-provide the image file on the command line or select it using the GUI.""")
-
-    options, args = parser.parse_args(sys.argv)
-    image_file = args[1] if len(args) > 1 else ''
-    dw = DeployWindow(image_file)
-
-if __name__ == '__main__':
-    try:
-        main()
-        gtk.main()
-    except Exception:
-        import traceback
-        traceback.print_exc()
lib/bb/ui/crumbs/__init__.py deleted +0 -17
deleted file mode 100644
index b7cbe1a..0000000
@@ -1,17 +0,0 @@
-#
-# Gtk+ UI pieces for BitBake
-#
-# Copyright (C) 2006-2007 Richard Purdie
-#
-# 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.
lib/bb/ui/crumbs/hig/__init__.py deleted +0 -0
deleted file mode 100644
index e69de29..0000000
lib/bb/ui/crumbs/hig/crumbsdialog.py deleted +0 -44

44 lines not on this page · raw message

lib/bb/ui/crumbs/hig/crumbsmessagedialog.py deleted +0 -70

70 lines not on this page · raw message

lib/bb/ui/crumbs/hig/deployimagedialog.py deleted +0 -219

219 lines not on this page · raw message

lib/bb/ui/crumbs/hig/imageselectiondialog.py deleted +0 -172

172 lines not on this page · raw message

lib/bb/ui/crumbs/hig/layerselectiondialog.py deleted +0 -298

298 lines not on this page · raw message

lib/bb/ui/crumbs/hig/propertydialog.py deleted +0 -437

437 lines not on this page · raw message

lib/bb/ui/crumbs/hig/settingsuihelper.py deleted +0 -122

122 lines not on this page · raw message

lib/bb/ui/crumbs/hobcolor.py deleted +0 -38
deleted file mode 100644
index 3316542..0000000
@@ -1,38 +0,0 @@
-#
-# BitBake Graphical GTK User Interface
-#
-# Copyright (C) 2012        Intel Corporation
-#
-# Authored by Shane Wang <[email protected]>
-#
-# 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.
-
-class HobColors:
-    WHITE        = "#ffffff"
-    PALE_GREEN   = "#aaffaa"
-    ORANGE       = "#eb8e68"
-    PALE_RED     = "#ffaaaa"
-    GRAY         = "#aaaaaa"
-    LIGHT_GRAY   = "#dddddd"
-    SLIGHT_DARK  = "#5f5f5f"
-    DARK         = "#3c3b37"
-    BLACK        = "#000000"
-    PALE_BLUE    = "#53b8ff"
-    DEEP_RED     = "#aa3e3e"
-    KHAKI        = "#fff68f"
-
-    OK = WHITE
-    RUNNING = PALE_GREEN
-    WARNING = ORANGE
-    ERROR = PALE_RED
lib/bb/ui/crumbs/hobwidget.py deleted +0 -904

904 lines not on this page · raw message

lib/bb/ui/crumbs/persistenttooltip.py deleted +0 -186

186 lines not on this page · raw message

lib/bb/ui/crumbs/progress.py deleted +0 -23
deleted file mode 100644
index 1d28a11..0000000
@@ -1,23 +0,0 @@
-import gtk
-
-class ProgressBar(gtk.Dialog):
-    def __init__(self, parent):
-
-        gtk.Dialog.__init__(self, flags=(gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT))
-        self.set_title("Parsing metadata, please wait...")
-        self.set_default_size(500, 0)
-        self.set_transient_for(parent)
-        self.progress = gtk.ProgressBar()
-        self.vbox.pack_start(self.progress)
-        self.show_all()
-
-    def set_text(self, msg):
-        self.progress.set_text(msg)
-
-    def update(self, x, y):
-        self.progress.set_fraction(float(x)/float(y))
-        self.progress.set_text("%2d %%" % (x*100/y))
-
-    def pulse(self):
-        self.progress.set_text("Loading...")
-        self.progress.pulse()
lib/bb/ui/crumbs/progressbar.py deleted +0 -60

60 lines not on this page · raw message

lib/bb/ui/crumbs/puccho.glade deleted +0 -606

283 lines not on this page · raw message

lib/bb/ui/crumbs/runningbuild.py deleted +0 -551

551 lines not on this page · raw message

lib/bb/ui/crumbs/utils.py deleted +0 -34
deleted file mode 100644
index 939864f..0000000

Lines of this file are not shown. View the raw message.

lib/bb/ui/goggle.py deleted +0 -126

126 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.5.0

Part of the diff is not shown here. View the raw message.

#8 lore raw

PATCH 9/28 data/event/siggen: Fix various exceptions [FIXME]

In reply to Richard Purdie
---
 lib/bb/data.py   | 1 +
 lib/bb/event.py  | 3 ++-
 lib/bb/siggen.py | 3 ++-
 3 files changed, 5 insertions(+), 2 deletions(-)
lib/bb/data.py +1 -0
index 48d990d..60b2033 100644
@@ -410,6 +410,7 @@ def build_dependencies(key, keys, shelldeps, varflagsexcl, d):
         deps -= set(varflags.get("vardepsexclude", "").split())
     except Exception as e:
         bb.warn("Exception during build_dependencies for %s" % key)
+        bb.warn(str(e))
         raise
     return deps, value
     #bb.note("Variable %s references %s and calls %s" % (key, str(deps), str(execs)))
lib/bb/event.py +2 -1
index 6fb3712..023300b 100644
@@ -157,7 +157,8 @@ def fire_ui_handlers(event, d):
                 _ui_handlers[h].event.sendpickle((pickle.dumps(event)))
              else:
                 _ui_handlers[h].event.send(event)
-        except:
+        except Exception as e:
+            print(str(e))
             errors.append(h)
     for h in errors:
         del _ui_handlers[h]
lib/bb/siggen.py +2 -1
index db3daef..f951020 100644
@@ -149,8 +149,9 @@ class SignatureGeneratorBasic(SignatureGenerator):
 
         try:
             taskdeps = self._build_data(fn, d)
-        except:
+        except Exception as e:
             bb.warn("Error during finalise of %s" % fn)
+            bb.error(str(e))
             raise
 
         #Slow but can be useful for debugging mismatched basehashes
Signature · 1 line
2.5.0
#9 lore raw

Re: [PATCH 09/28] data/event/siggen: Fix various exceptions [FIXME]

Quoted 6 lines · Richard Purdie
---
 lib/bb/data.py   | 1 +
 lib/bb/event.py  | 3 ++-
 lib/bb/siggen.py | 3 ++-
 3 files changed, 5 insertions(+), 2 deletions(-)

Ignore this patch, it shouldn't have been included. This one notes some areas we really need to improve the exception handling. I need to clean it up and resend as a separate issue.

Cheers,

Richard

#10 lore raw

PATCH 10/28 toaster: use force_text instead of force_bytes

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Usage of force_bytes in BuildRequest.__str__ method caused python 3 to throw "__str__ returned non-string (type bytes)" error.

Replaced force_bytes with force_text to make the code working on both python 2 and python 3.

[YOCTO #9584]

---
 lib/toaster/bldcontrol/management/commands/runbuilds.py | 4 ++--
 lib/toaster/bldcontrol/models.py                        | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)
lib/toaster/bldcontrol/management/commands/runbuilds.py +2 -2
index e3145e8..80782ef 100644
@@ -54,8 +54,8 @@ class Command(NoArgsCommand):
                 logger.debug("runbuilds: No build env")
                 return
 
-            logger.debug("runbuilds: starting build %s, environment %s" % \
-                         (str(br).decode('utf-8'), bec.be))
+            logger.info("runbuilds: starting build %s, environment %s" % \
+                        (br, bec.be))
 
             # let the build request know where it is being executed
             br.environment = bec.be
lib/toaster/bldcontrol/models.py +2 -2
index e09ad20..f06c562 100644
@@ -1,7 +1,7 @@
 from __future__ import unicode_literals
 from django.db import models
 from django.core.validators import MaxValueValidator, MinValueValidator
-from django.utils.encoding import force_bytes
+from django.utils.encoding import force_text
 from orm.models import Project, ProjectLayer, ProjectVariable, ProjectTarget, Build, Layer_Version
 
 import logging
@@ -121,7 +121,7 @@ class BuildRequest(models.Model):
         return self.brvariable_set.get(name="MACHINE").value
 
     def __str__(self):
-        return force_bytes('%s %s' % (self.project, self.get_state_display()))
+        return force_text('%s %s' % (self.project, self.get_state_display()))
 
 # These tables specify the settings for running an actual build.
 # They MUST be kept in sync with the tables in orm.models.Project*
Signature · 1 line
2.5.0
#11 lore raw

PATCH 11/28 toaster: get rid of using reduce

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Replaced compicated calls of reduce with more clear code. As reduce was removed from python 3 this change is mandatory for the code to work on both pythons.

Here is an example change for illustration purposes:

original code:

querydict = dict(zip(or_keys, or_values))
query = reduce(operator.or_, map(lambda x: __get_q_for_val(x, querydict[x]), [k for k in querydict])))

replaced with:

query = None
for key, val in zip(or_keys, or_values):
x = __get_q_for_val(k, val)
query = query | x if query else x

[YOCTO #9584]

---
 lib/toaster/toastergui/views.py   | 64 +++++++++++++++++++++++++++------------
 lib/toaster/toastergui/widgets.py | 20 +++++++-----
 2 files changed, 57 insertions(+), 27 deletions(-)
lib/toaster/toastergui/views.py +44 -20
index e78b0da..22d1a0c 100755
@@ -229,10 +229,18 @@ OR_VALUE_SEPARATOR = "|"
 DESCENDING = "-"
 
 def __get_q_for_val(name, value):
-    if "OR" in value:
-        return reduce(operator.or_, map(lambda x: __get_q_for_val(name, x), [ x for x in value.split("OR") ]))
+    if "OR" in value or "AND" in value:
+        result = None
+        for x in value.split("OR"):
+             x = __get_q_for_val(name, x)
+             result = result | x if result else x
+        return result
     if "AND" in value:
-        return reduce(operator.and_, map(lambda x: __get_q_for_val(name, x), [ x for x in value.split("AND") ]))
+        result = None
+        for x in value.split("AND"):
+            x = __get_q_for_val(name, x)
+            result = result & x if result else x
+        return result
     if value.startswith("NOT"):
         value = value[3:]
         if value == 'None':
@@ -251,14 +259,18 @@ def _get_filtering_query(filter_string):
     and_keys = search_terms[0].split(AND_VALUE_SEPARATOR)
     and_values = search_terms[1].split(AND_VALUE_SEPARATOR)
 
-    and_query = []
+    and_query = None
     for kv in zip(and_keys, and_values):
         or_keys = kv[0].split(OR_VALUE_SEPARATOR)
         or_values = kv[1].split(OR_VALUE_SEPARATOR)
-        querydict = dict(zip(or_keys, or_values))
-        and_query.append(reduce(operator.or_, map(lambda x: __get_q_for_val(x, querydict[x]), [k for k in querydict])))
+        query = None
+        for key, val in zip(or_keys, or_values):
+            x = __get_q_for_val(k, val)
+            query = query | x if query else x
 
-    return reduce(operator.and_, [k for k in and_query])
+        and_query = and_query & query if and_query else query
+
+    return and_query
 
 def _get_toggle_order(request, orderkey, toggle_reverse = False):
     if toggle_reverse:
@@ -295,21 +307,24 @@ def _validate_input(field_input, model):
         # Check we are looking for a valid field
         valid_fields = model._meta.get_all_field_names()
         for field in field_input_list[0].split(AND_VALUE_SEPARATOR):
-            if not reduce(lambda x, y: x or y, [ field.startswith(x) for x in valid_fields ]):
-                return None, (field, [ x for x in valid_fields ])
+            if True in [field.startswith(x) for x in valid_fields]:
+                break
+        else:
+           return None, (field, valid_fields)
 
     return field_input, invalid
 
 # uses search_allowed_fields in orm/models.py to create a search query
 # for these fields with the supplied input text
 def _get_search_results(search_term, queryset, model):
-    search_objects = []
+    search_object = None
     for st in search_term.split(" "):
-        q_map = map(lambda x: Q(**{x+'__icontains': st}),
-                model.search_allowed_fields)
+        queries = None
+        for field in model.search_allowed_fields:
+            query =  Q(**{x+'__icontains': st})
+            queries = queries | query if queries else query
 
-        search_objects.append(reduce(operator.or_, q_map))
-    search_object = reduce(operator.and_, search_objects)
+        search_object = search_object & queries if search_object else queries
     queryset = queryset.filter(search_object)
 
     return queryset
@@ -1938,10 +1953,10 @@ if True:
                 if ptype == "build":
                     mandatory_fields.append('projectversion')
                 # make sure we have values for all mandatory_fields
-                if reduce( lambda x, y: x or y, map(lambda x: len(request.POST.get(x, '')) == 0, mandatory_fields)):
-                # set alert for missing fields
-                    raise BadParameterException("Fields missing: " +
-            ", ".join([x for x in mandatory_fields if len(request.POST.get(x, '')) == 0 ]))
+                missing = [field for field in mandatory_fields if len(request.POST.get(field, '')) == 0]
+                if missing:
+                    # set alert for missing fields
+                    raise BadParameterException("Fields missing: %s" % ", ".join(missing))
 
                 if not request.user.is_authenticated():
                     user = authenticate(username = request.POST.get('username', '_anonuser'), password = 'nopass')
@@ -2035,13 +2050,22 @@ if True:
         from collections import Counter
         freqtargets = []
         try:
-            freqtargets += map(lambda x: x.target, reduce(lambda x, y: x + y,   map(lambda x: list(x.target_set.all()), Build.objects.filter(project = prj, outcome__lt = Build.IN_PROGRESS))))
-            freqtargets += map(lambda x: x.target, reduce(lambda x, y: x + y,   map(lambda x: list(x.brtarget_set.all()), BuildRequest.objects.filter(project = prj, state = BuildRequest.REQ_FAILED))))
+            btargets = sum(build.target_set.all() for build in Build.objects.filter(project=prj, outcome__lt=Build.IN_PROGRESS))
+            brtargets = sum(br.brtarget_set.all() for br in BuildRequest.objects.filter(project = prj, state = BuildRequest.REQ_FAILED))
+            freqtargets = [x.target for x in btargets] + [x.target for x in brtargets]
         except TypeError:
             pass
         freqtargets = Counter(freqtargets)
         freqtargets = sorted(freqtargets, key = lambda x: freqtargets[x], reverse=True)
 
+        layers = [{"id": x.layercommit.pk, "orderid": x.pk, "name" : x.layercommit.layer.name,
+                   "vcs_url": x.layercommit.layer.vcs_url, "vcs_reference" : x.layercommit.get_vcs_reference(),
+                   "url": x.layercommit.layer.layer_index_url, "layerdetailurl": x.layercommit.get_detailspage_url(prj.pk),
+                   # This branch name is actually the release
+                   "branch" : {"name" : x.layercommit.get_vcs_reference(),
+                               "layersource" : x.layercommit.up_branch.layer_source.name if x.layercommit.up_branch != None else None}
+                   } for x in prj.projectlayer_set.all().order_by("id")]
+
         context = {
             "project" : prj,
             "lvs_nos" : Layer_Version.objects.all().count(),
lib/toaster/toastergui/widgets.py +13 -7
index 4117031..0f972d9 100644
@@ -239,14 +239,20 @@ class ToasterTable(TemplateView):
             raise Exception("Search fields aren't defined in the model %s"
                             % self.queryset.model)
 
-        search_queries = []
+        search_queries = None
         for st in search_term.split(" "):
-            q_map = [Q(**{field + '__icontains': st})
-                     for field in self.queryset.model.search_allowed_fields]
-
-            search_queries.append(reduce(operator.or_, q_map))
-
-        search_queries = reduce(operator.and_, search_queries)
+            queries = None
+            for field in self.queryset.model.search_allowed_fields:
+                query = Q(**{field + '__icontains': st})
+                if queries:
+                    queries |= query
+                else:
+                    queries = query
+
+            if search_queries:
+               search_queries &= queries
+            else:
+               search_queries = queries
 
         self.queryset = self.queryset.filter(search_queries)
 
Signature · 1 line
2.5.0
#12 lore raw

PATCH 12/28 toaster: fix imports to work for python 3

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Some APIs have been moved to other modules in python 3:
getstatusoutput: moved from commands to subproces
urlopen: moved from urllib2 to urllib.request
urlparse: moved from urlparse to urllib.parse

Made the imports work for both python versions by catching ImportError and importing APIs from different modules.

[YOCTO #9584]

---
 lib/bb/utils.py           |  1 -
 lib/toaster/orm/models.py | 16 ++++++++++++----
 2 files changed, 12 insertions(+), 5 deletions(-)
lib/bb/utils.py +0 -1
index 138da44..8f75871 100644
@@ -41,7 +41,6 @@ from subprocess import getstatusoutput
 from contextlib import contextmanager
 from ctypes import cdll
 
-
 logger = logging.getLogger("BitBake.Util")
 python_extensions = [e for e, _, _ in imp.get_suffixes()]
 
lib/toaster/orm/models.py +12 -4
index 88967a2..9183b0c 100644
@@ -1147,18 +1147,26 @@ class LayerIndexLayerSource(LayerSource):
         assert self.apiurl is not None
         from django.db import transaction, connection
 
-        import urllib2, urlparse, json
+        import json
         import os
+
+        try:
+            from urllib.request import urlopen, URLError
+            from urllib.parse import urlparse
+        except ImportError:
+            from urllib2 import urlopen, URLError
+            from urlparse import urlparse
+
         proxy_settings = os.environ.get("http_proxy", None)
         oe_core_layer = 'openembedded-core'
 
         def _get_json_response(apiurl = self.apiurl):
-            _parsedurl = urlparse.urlparse(apiurl)
+            _parsedurl = urlparse(apiurl)
             path = _parsedurl.path
 
             try:
-                res = urllib2.urlopen(apiurl)
-            except urllib2.URLError as e:
+                res = urlopen(apiurl)
+            except URLError as e:
                 raise Exception("Failed to read %s: %s" % (path, e.reason))
 
             return json.loads(res.read())
Signature · 1 line
2.5.0
#13 lore raw

PATCH 13/28 toaster: fix local imports

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Replaced local imports with absolute imports.
Used .module for local imports.

This should make the code to work on python 2 and python 3.

[YOCTO #9584]

---
 lib/toaster/bldcontrol/bbcontroller.py                      | 2 +-
 lib/toaster/bldcontrol/localhostbecontroller.py             | 2 +-
 lib/toaster/bldcontrol/management/commands/checksettings.py | 2 +-
 lib/toaster/bldcontrol/management/commands/loadconf.py      | 2 +-
 4 files changed, 4 insertions(+), 4 deletions(-)
lib/toaster/bldcontrol/bbcontroller.py +1 -1
index d09ac17..9bddadb 100644
@@ -79,7 +79,7 @@ def getBuildEnvironmentController(**kwargs):
         The return object MUST always be a BuildEnvironmentController.
     """
 
-    from localhostbecontroller import LocalhostBEController
+    from bldcontrol.localhostbecontroller import LocalhostBEController
 
     be = BuildEnvironment.objects.filter(Q(**kwargs))[0]
     if be.betype == BuildEnvironment.TYPE_LOCAL:
lib/toaster/bldcontrol/localhostbecontroller.py +1 -1
index 7b2f126..b4e4196 100644
@@ -32,7 +32,7 @@ import subprocess
 
 from toastermain import settings
 
-from bbcontroller import BuildEnvironmentController, ShellCmdException, BuildSetupException, BitbakeController
+from bldcontrol.bbcontroller import BuildEnvironmentController, ShellCmdException, BuildSetupException, BitbakeController
 
 import logging
 logger = logging.getLogger("toaster")
lib/toaster/bldcontrol/management/commands/checksettings.py +1 -1
index 6b1da1b..2407e1b 100644
@@ -105,7 +105,7 @@ class Command(NoArgsCommand):
                     try:
                         config_file = os.environ.get('TOASTER_CONF')
                         print("\nImporting file: %s" % config_file)
-                        from loadconf import Command as LoadConfigCommand
+                        from .loadconf import Command as LoadConfigCommand
 
                         LoadConfigCommand()._import_layer_config(config_file)
                         # we run lsupdates after config update
lib/toaster/bldcontrol/management/commands/loadconf.py +1 -1
index 5022b59..6d25df9 100644
@@ -4,7 +4,7 @@ from orm.models import BitbakeVersion, Release, ReleaseDefaultLayer, ReleaseLaye
 from django.db import IntegrityError
 import os
 
-from checksettings import DN
+from .checksettings import DN
 
 import logging
 logger = logging.getLogger("toaster")
Signature · 1 line
2.5.0
#14 lore raw

PATCH 14/28 toaster: modified list of dependencies

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Removed dependency to argparse and wsgiref as they're in standard python library.

wsgiref crashes during installation with python 3 as it's not compatible with python 3.

Added dependency to pytz as it's used in the toaster code.

---
 toaster-requirements.txt | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
toaster-requirements.txt +1 -2
index 0e8c742..e61c8e2 100644
@@ -1,4 +1,3 @@
 Django>1.8,<1.9
-argparse==1.2.1
-wsgiref==0.1.2
 beautifulsoup4>=4.4.0
+pytz
Signature · 1 line
2.5.0
#15 lore raw

PATCH 15/28 toaster: use decode('utf-8') for binary data

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Decoded binary data to utf-8 to fix the following error when runnign on python 3:
TypeError: Type str doesn't support the buffer API

[YOCTO #9584]

---
 lib/toaster/bldcontrol/localhostbecontroller.py        | 2 +-
 lib/toaster/bldcontrol/management/commands/loadconf.py | 2 +-
 lib/toaster/orm/models.py                              | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)
lib/toaster/bldcontrol/localhostbecontroller.py +1 -1
index b4e4196..3da8be4 100644
@@ -70,7 +70,7 @@ class LocalhostBEController(BuildEnvironmentController):
             raise ShellCmdException(err)
         else:
             logger.debug("localhostbecontroller: shellcmd success")
-            return out
+            return out.decode('utf-8')
 
     def getGitCloneDirectory(self, url, branch):
         """Construct unique clone directory name out of url and branch."""
lib/toaster/bldcontrol/management/commands/loadconf.py +1 -1
index 6d25df9..173e3ce 100644
@@ -54,7 +54,7 @@ class Command(BaseCommand):
             (out,err) = cmd.communicate()
             if cmd.returncode != 0:
                 logging.warning("Error while importing layer vcs_url: git error: %s" % err)
-            for line in out.split("\n"):
+            for line in out.decode('utf-8').split("\n"):
                 try:
                     (name, path) = line.split("\t", 1)
                     if name == remote_name:
lib/toaster/orm/models.py +1 -1
index 9183b0c..58dc753 100644
@@ -1169,7 +1169,7 @@ class LayerIndexLayerSource(LayerSource):
             except URLError as e:
                 raise Exception("Failed to read %s: %s" % (path, e.reason))
 
-            return json.loads(res.read())
+            return json.loads(res.read().decode('utf-8'))
 
         # verify we can get the basic api
         try:
Signature · 1 line
2.5.0
#16 lore raw

PATCH 16/28 toaster: use items and range instead of old APIs

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Used items() and range() APIs instead of iteritems() and xrange() as latter don't exist in python 3

[YOCTO #9584]

---
 lib/toaster/contrib/tts/config.py     | 2 +-
 lib/toaster/orm/models.py             | 2 +-
 lib/toaster/toastergui/tablefilter.py | 2 +-
 lib/toaster/toastergui/views.py       | 2 +-
 lib/toaster/toastergui/widgets.py     | 4 ++--
 5 files changed, 6 insertions(+), 6 deletions(-)
lib/toaster/contrib/tts/config.py +1 -1
index 40d45f3..87b427c 100644
@@ -74,7 +74,7 @@ BACKLOGFILE = os.path.join(os.path.dirname(__file__), "backlog.txt")
 # task states
 def enum(*sequential, **named):
     enums = dict(zip(sequential, range(len(sequential))), **named)
-    reverse = dict((value, key) for key, value in enums.iteritems())
+    reverse = dict((value, key) for key, value in enums.items())
     enums['reverse_mapping'] = reverse
     return type('Enum', (), enums)
 
lib/toaster/orm/models.py +1 -1
index 58dc753..ee01a46 100644
@@ -103,7 +103,7 @@ class GitURLValidator(validators.URLValidator):
 
 def GitURLField(**kwargs):
     r = models.URLField(**kwargs)
-    for i in xrange(len(r.validators)):
+    for i in range(len(r.validators)):
         if isinstance(r.validators[i], validators.URLValidator):
             r.validators[i] = GitURLValidator()
     return r
lib/toaster/toastergui/tablefilter.py +1 -1
index 9d15bcf..65454e1 100644
@@ -286,7 +286,7 @@ class TableFilterMap(object):
     def to_json(self, queryset):
         data = {}
 
-        for filter_name, table_filter in self.__filters.iteritems():
+        for filter_name, table_filter in self.__filters.items():
             data[filter_name] = table_filter.to_json()
 
         return data
lib/toaster/toastergui/views.py +1 -1
index 22d1a0c..b256db7 100755
@@ -2279,7 +2279,7 @@ if True:
         # Strip trailing/leading whitespace from all values
         # put into a new dict because POST one is immutable
         post_data = dict()
-        for key,val in request.POST.iteritems():
+        for key,val in request.POST.items():
           post_data[key] = val.strip()
 
 
lib/toaster/toastergui/widgets.py +2 -2
index 0f972d9..19850fb 100644
@@ -278,12 +278,12 @@ class ToasterTable(TemplateView):
         # Make a unique cache name
         cache_name = self.__class__.__name__
 
-        for key, val in request.GET.iteritems():
+        for key, val in request.GET.items():
             if key == 'nocache':
                 continue
             cache_name = cache_name + str(key) + str(val)
 
-        for key, val in kwargs.iteritems():
+        for key, val in kwargs.items():
             cache_name = cache_name + str(key) + str(val)
 
         # No special chars allowed in the cache name apart from dash
Signature · 1 line
2.5.0
#17 lore raw

PATCH 17/28 toaster: replace map with list comprehensions

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

map returns map object in python 3. Replaced calls of map to equivalent list comprehensions in the code which requires lists.

[YOCTO #9584]

---
 lib/toaster/orm/models.py        |  2 +-
 lib/toaster/toastergui/tables.py |  3 +--
 lib/toaster/toastergui/views.py  | 45 ++++++++++++++++------------------------
 3 files changed, 20 insertions(+), 30 deletions(-)
lib/toaster/orm/models.py +1 -1
index ee01a46..dd64664 100644
@@ -1183,7 +1183,7 @@ class LayerIndexLayerSource(LayerSource):
 
         # update branches; only those that we already have names listed in the
         # Releases table
-        whitelist_branch_names = map(lambda x: x.branch_name, Release.objects.all())
+        whitelist_branch_names = [rel.branch_name for rel in Release.objects.all()]
         if len(whitelist_branch_names) == 0:
             raise Exception("Failed to make list of branches to fetch")
 
lib/toaster/toastergui/tables.py +1 -2
index d21bed1..caa2fba 100644
@@ -333,8 +333,7 @@ class RecipesTable(ToasterTable):
         context = super(RecipesTable, self).get_context_data(**kwargs)
 
         context['project'] = project
-
-        context['projectlayers'] = map(lambda prjlayer: prjlayer.layercommit.id, ProjectLayer.objects.filter(project=context['project']))
+        context['projectlayers'] = [player.layercommit.id for player in ProjectLayer.objects.filter(project=context['project'])]
 
         return context
 
lib/toaster/toastergui/views.py +18 -27

86 lines not on this page · raw message

Signature · 1 line
2.5.0
#18 lore raw

PATCH 18/28 toaster: use re.sub() instead of translate()

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

translate has different set of parameters in python 3 and can't be used the way it's used in toaster api module.

Replacing it with re.sub() should make the code work in both python 2 and python 3.

[YOCTO #9584]

---
 lib/toaster/toastergui/api.py | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
lib/toaster/toastergui/api.py +2 -1
index 42901f7..961b594 100644
@@ -18,6 +18,7 @@
 
 
 # Temporary home for the UI's misc API
+import re
 
 from orm.models import Project, ProjectTarget, Build
 from bldcontrol.models import BuildRequest
@@ -92,7 +93,7 @@ class XhrBuildRequest(View):
         if 'targets' in request.POST:
             ProjectTarget.objects.filter(project = project).delete()
             s = str(request.POST['targets'])
-            for t in s.translate(None, ";%|\"").split(" "):
+            for t in re.sub(r'[;%|"]', '', s).split(" "):
                 if ":" in t:
                     target, task = t.split(":")
                 else:
Signature · 1 line
2.5.0
#19 lore raw

PATCH 19/28 toaster: read timezone files in binary mode

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Used 'rb' mode to open files to avoid unicode error when code runs on python 3:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80
in position 44: invalid start byte

[YOCTO #9584]

---
 lib/toaster/toastermain/settings.py | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
lib/toaster/toastermain/settings.py +3 -4
index c7edff2..3dfa2b2 100644
@@ -87,17 +87,16 @@ else:
             try:
                 import pytz
                 from pytz.exceptions import UnknownTimeZoneError
-                pass
                 try:
                     if pytz.timezone(zonename) is not None:
-                        zonefilelist[hashlib.md5(open(filepath).read()).hexdigest()] = zonename
+                        zonefilelist[hashlib.md5(open(filepath, 'rb').read()).hexdigest()] = zonename
                 except UnknownTimeZoneError as ValueError:
                     # we expect timezone failures here, just move over
                     pass
             except ImportError:
-                zonefilelist[hashlib.md5(open(filepath).read()).hexdigest()] = zonename
+                zonefilelist[hashlib.md5(open(filepath, 'rb').read()).hexdigest()] = zonename
 
-    TIME_ZONE = zonefilelist[hashlib.md5(open('/etc/localtime').read()).hexdigest()]
+    TIME_ZONE = zonefilelist[hashlib.md5(open('/etc/localtime', 'rb').read()).hexdigest()]
 
 # Language code for this installation. All choices can be found here:
 # http://www.i18nguy.com/unicode/language-identifiers.html
Signature · 1 line
2.5.0
#20 lore raw

PATCH 20/28 toaster: moved import bb.server.xmlrpc

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Moved import xmlrpc module to the place where it's used to avoid toaster crashes when importing bitbake code.

NOTE: This patch is made to be able to partly test toaster with bitbake from master. It can be removed as soon as bb.server.xmlrpc is ported to python 3.

---
 lib/toaster/bldcontrol/bbcontroller.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/toaster/bldcontrol/bbcontroller.py +1 -1
index 9bddadb..912f67b 100644
@@ -30,7 +30,6 @@ from bldcontrol.models import BuildEnvironment, BRLayer, BRVariable, BRTarget, B
 # load Bitbake components
 path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
 sys.path.insert(0, path)
-import bb.server.xmlrpc
 
 class BitbakeController(object):
     """ This is the basic class that controlls a bitbake server.
@@ -38,6 +37,7 @@ class BitbakeController(object):
     """
 
     def __init__(self, be):
+        import bb.server.xmlrpc
         self.connection = bb.server.xmlrpc._create_server(be.bbaddress,
                                                           int(be.bbport))[0]
 
Signature · 1 line
2.5.0
#21 lore raw

PATCH 21/28 toaster: fix migrations

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Created two new migrations due to the models changes made in python3 patchset.

---
 .../migrations/0004_auto_20160509_0946.py          | 34 +++++++++
 .../orm/migrations/0007_auto_20160509_0946.py      | 89 ++++++++++++++++++++++
 2 files changed, 123 insertions(+)
 create mode 100644 bitbake/lib/toaster/bldcontrol/migrations/0004_auto_20160509_0946.py
 create mode 100644 bitbake/lib/toaster/orm/migrations/0007_auto_20160509_0946.py
bitbake/lib/toaster/bldcontrol/migrations/0004_auto_20160509_0946.py new file +34 -0
new file mode 100644
index 0000000..4a70e2d
@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('bldcontrol', '0003_add_cancelling_state'),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name='buildenvironment',
+            name='bbstate',
+            field=models.IntegerField(choices=[(0, 'stopped'), (1, 'started')], default=0),
+        ),
+        migrations.AlterField(
+            model_name='buildenvironment',
+            name='betype',
+            field=models.IntegerField(choices=[(0, 'local')]),
+        ),
+        migrations.AlterField(
+            model_name='buildenvironment',
+            name='lock',
+            field=models.IntegerField(choices=[(0, 'free'), (1, 'lock'), (2, 'running')], default=0),
+        ),
+        migrations.AlterField(
+            model_name='buildrequest',
+            name='state',
+            field=models.IntegerField(choices=[(0, 'created'), (1, 'queued'), (2, 'in progress'), (3, 'completed'), (4, 'failed'), (5, 'deleted'), (6, 'cancelling'), (7, 'archive')], default=0),
+        ),
+    ]
bitbake/lib/toaster/orm/migrations/0007_auto_20160509_0946.py new file +89 -0

89 lines not on this page · raw message

Signature · 1 line
2.5.0
#22 lore raw

PATCH 22/28 toaster: use knotty when working with bitbake server

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Using empty BITBAKE_UI environment variable causes bitbake server to fail with the error:
FATAL: Unable to import extension module "" from bb.ui
Valid extension modules: knotty or toasterui\n'

Used BITBAKE_UI="knotty" when starting and stoping bitbake server to solve above issue.

---
 lib/toaster/bldcontrol/localhostbecontroller.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
lib/toaster/bldcontrol/localhostbecontroller.py +2 -2
index 3da8be4..9364900 100644
@@ -287,7 +287,7 @@ class LocalhostBEController(BuildEnvironmentController):
 
         # run bitbake server from the clone
         bitbake = os.path.join(self.pokydirname, 'bitbake', 'bin', 'bitbake')
-        self._shellcmd('bash -c \"source %s %s; BITBAKE_UI="" %s --read %s '
+        self._shellcmd('bash -c \"source %s %s; BITBAKE_UI="knotty" %s --read %s '
                        '--server-only -t xmlrpc -B 0.0.0.0:0\"' % (oe_init,
                        builddir, bitbake, confpath), self.be.sourcedir)
 
@@ -324,7 +324,7 @@ class LocalhostBEController(BuildEnvironmentController):
                                      'bitbake')
         self._shellcmd(['bash -c \"(TOASTER_BRBE="%s" BBSERVER="0.0.0.0:-1" '
                         '%s %s -u toasterui --token="" >>%s 2>&1;'
-                        'BITBAKE_UI="" BBSERVER=0.0.0.0:-1 %s -m)&\"' \
+                        'BITBAKE_UI="knotty" BBSERVER=0.0.0.0:-1 %s -m)&\"' \
                         % (brbe, local_bitbake, bbtargets, log, bitbake)],
                         builddir, nowait=True)
 
Signature · 1 line
2.5.0
#23 lore raw

PATCH 23/28 xmlrpc: add parameter use_builtin_types

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Added use_builtin_types parameter to XMLRPCProxyServer.__init__ to fix this error:
ERROR: Could not connect to server 0.0.0.0:37132
: __init__() got an unexpected keyword argument 'use_builtin_types'

---
 lib/bb/server/xmlrpc.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/bb/server/xmlrpc.py +1 -1
index 146ca17..57c59a8 100644
@@ -180,7 +180,7 @@ class XMLRPCProxyServer(BaseImplServer):
     """ not a real working server, but a stub for a proxy server connection
 
     """
-    def __init__(self, host, port):
+    def __init__(self, host, port, use_builtin_types=True):
         self.host = host
         self.port = port
 
Signature · 1 line
2.5.0
#24 lore raw

PATCH 24/28 Revert "buildinfohelper: work around unicode exceptions"

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

This commit causes buildinfohelper to crash when run on python 3 as python 3 doesn't have unicode builtin function.

This reverts commit 7a309d964a86f3474eaab7df6d438ed797f935c0.

---
 lib/bb/ui/buildinfohelper.py | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
lib/bb/ui/buildinfohelper.py +4 -6
index cea53e0..d59d6a5 100644
@@ -494,7 +494,7 @@ class ORMWrapper(object):
             parent_obj = self._cached_get(Target_File, target = target_obj, path = parent_path, inodetype = Target_File.ITYPE_DIRECTORY)
             tf_obj = Target_File.objects.create(
                         target = target_obj,
-                        path = unicode(path, 'utf-8'),
+                        path = path,
                         size = size,
                         inodetype = Target_File.ITYPE_DIRECTORY,
                         permission = permission,
@@ -519,7 +519,7 @@ class ORMWrapper(object):
 
             tf_obj = Target_File.objects.create(
                         target = target_obj,
-                        path = unicode(path, 'utf-8'),
+                        path = path,
                         size = size,
                         inodetype = inodetype,
                         permission = permission,
@@ -550,9 +550,7 @@ class ORMWrapper(object):
                 filetarget_path = "/".join(fcpl)
 
             try:
-                filetarget_obj = Target_File.objects.get(
-                                     target = target_obj,
-                                     path = unicode(filetarget_path, 'utf-8'))
+                filetarget_obj = Target_File.objects.get(target = target_obj, path = filetarget_path)
             except Target_File.DoesNotExist:
                 # we might have an invalid link; no way to detect this. just set it to None
                 filetarget_obj = None
@@ -561,7 +559,7 @@ class ORMWrapper(object):
 
             tf_obj = Target_File.objects.create(
                         target = target_obj,
-                        path = unicode(path, 'utf-8'),
+                        path = path,
                         size = size,
                         inodetype = Target_File.ITYPE_SYMLINK,
                         permission = permission,
Signature · 1 line
2.5.0
#25 lore raw

PATCH 25/28 toaster: use // operator instead of /

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Division operator works differently in Python 3. It results in float unlike in Python 2, where it results in int.

Explicitly used "floor division" operator instead of 'division' operator. This should make the code to result in integer under both pythons.

---
 lib/toaster/orm/models.py                          | 2 +-
 lib/toaster/toastergui/templatetags/projecttags.py | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
lib/toaster/orm/models.py +1 -1
index dd64664..25bc1db 100644
@@ -424,7 +424,7 @@ class Build(models.Model):
         tf = Task.objects.filter(build = self)
         tfc = tf.count()
         if tfc > 0:
-            completeper = tf.exclude(order__isnull=True).count()*100/tfc
+            completeper = tf.exclude(order__isnull=True).count()*100 // tfc
         else:
             completeper = 0
         return completeper
lib/toaster/toastergui/templatetags/projecttags.py +1 -1
index 75f2261..1d68036 100644
@@ -90,7 +90,7 @@ def whitespace_space_filter(value, arg):
 def divide(value, arg):
     if int(arg) == 0:
         return -1
-    return int(value) / int(arg)
+    return int(value) // int(arg)
 
 @register.filter
 def multiply(value, arg):
Signature · 1 line
2.5.0
#26 lore raw

PATCH 26/28 toaster: don't use mru.count in the template

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

mru is a list. It has a count method, but it differs from the one for the queryset. Using mru.count causes 'Latest project builds' section to silently disappear when toaster runs on python 3.

---
 lib/toaster/toastergui/templates/mrb_section.html | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/toaster/toastergui/templates/mrb_section.html +1 -1
index 212998a..2780ac5 100644
@@ -18,7 +18,7 @@
   });
 </script>
 
-{%if mru and mru.count > 0%}
+{%if mru %}
 
   {%if mrb_type == 'project' %}
       <h2 class="page-header">
Signature · 1 line
2.5.0
#27 lore raw

PATCH 27/28 toaster: fix urllib imports

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Some functions have been moved from urllib to urllib.parse in python 3. Modifying the code to import unquote, urlencode and unquote_plus from urllib.parse if import from urllib fails should make it working on both python 2 and python 3.

---
 lib/toaster/toastergui/views.py   | 9 ++++++---
 lib/toaster/toastergui/widgets.py | 6 +++++-
 2 files changed, 11 insertions(+), 4 deletions(-)
lib/toaster/toastergui/views.py +6 -3
index 8e920f0..0510897 100755
@@ -200,16 +200,19 @@ def _verify_parameters(g, mandatory_parameters):
     return None
 
 def _redirect_parameters(view, g, mandatory_parameters, *args, **kwargs):
-    import urllib
+    try:
+        from urllib import unquote, urlencode
+    except ImportError:
+        from urllib.parse import unquote, urlencode
     url = reverse(view, kwargs=kwargs)
     params = {}
     for i in g:
         params[i] = g[i]
     for i in mandatory_parameters:
         if not i in params:
-            params[i] = urllib.unquote(str(mandatory_parameters[i]))
+            params[i] = unquote(str(mandatory_parameters[i]))
 
-    return redirect(url + "?%s" % urllib.urlencode(params), permanent = False, **kwargs)
+    return redirect(url + "?%s" % urlencode(params), permanent = False, **kwargs)
 
 class RedirectException(Exception):
     def __init__(self, view, g, mandatory_parameters, *args, **kwargs):
lib/toaster/toastergui/widgets.py +5 -1
index 19850fb..551c33c 100644
@@ -38,7 +38,11 @@ import json
 import collections
 import operator
 import re
-import urllib
+
+try:
+    from urllib import unquote_plus
+except ImportError:
+    from urllib.parse import unquote_plus
 
 import logging
 logger = logging.getLogger("toaster")
Signature · 1 line
2.5.0
#28 lore raw

PATCH 28/28 toaster: use python3 explicitly

In reply to Richard Purdie

From: Ed Bartosh <[email protected]>

Explicitly used python3 as default python for oe builds will continue to be python2.

[YOCTO #9584]

---
 bin/toaster | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
bin/toaster +3 -3
index 05b7935..be1bb9c 100755
@@ -111,7 +111,7 @@ stop_system()
 
 verify_prereq() {
     # Verify Django version
-    reqfile=$(python -c "import os; print(os.path.realpath('$BBBASEDIR/toaster-requirements.txt'))")
+    reqfile=$(python3 -c "import os; print(os.path.realpath('$BBBASEDIR/toaster-requirements.txt'))")
     exp='s/Django\([><=]\+\)\([^,]\+\),\([><=]\+\)\(.\+\)/'
     exp=$exp'import sys,django;version=django.get_version().split(".");'
     exp=$exp'sys.exit(not (version \1 "\2".split(".") and version \3 "\4".split(".")))/p'
@@ -135,7 +135,7 @@ else
 fi
 
 export BBBASEDIR=`dirname $TOASTER`/..
-MANAGE=$BBBASEDIR/lib/toaster/manage.py
+MANAGE="python3 $BBBASEDIR/lib/toaster/manage.py"
 OEROOT=`dirname $TOASTER`/../..
 
 # this is the configuraton file we are using for toaster
@@ -162,7 +162,7 @@ fi
 
 if [ "$TOASTER_CONF" = "" ]; then
     TOASTER_CONF="$TEMPLATECONF/toasterconf.json"
-    export TOASTER_CONF=$(python -c "import os; print(os.path.realpath('$TOASTER_CONF'))")
+    export TOASTER_CONF=$(python3 -c "import os; print(os.path.realpath('$TOASTER_CONF'))")
 fi
 
 if [ ! -f $TOASTER_CONF ]; then
Signature · 1 line
2.5.0