<commit_before># Implement the pygame API for the bitmask functions

from math import atan2, pi

from pygame._sdl import sdl, ffi
from pygame.surflock import locked
from pygame.rect import Rect
from pygame.color import create_color

class Mask(object):
    """pygame.Mask((width, height)): return Mask

       pygame object for representing 2d bitmask"""

    def __init__(self, size):
        self._mask = sdl.bitmask_create(size[0], size[1])

    def __del__(self):
        if self._mask:
            sdl.bitmask_free(self._mask)

    def angle(self):
        """angle() -> theta

           Returns the orientation of the pixels"""
        xs = ys = tot = 0
        # multiplication counters
        xx = yy = xy = 0
        for x in range(self._mask.w):
            for y in range(self._mask.h):
                if sdl.bitmask_getbit(self._mask, x, y):
                    ys += y
                    xs += x
                    tot += 1
                    xx += x * x
                    yy += y * y
                    xy += x * y
        if tot:
            xc = xs // tot
            yc = ys // tot
            theta = atan2(2 * (xy / tot - xc * yc),
                          (xx / tot - xc * xc) - (yy / tot - yc * yc))
            # covert from radians
            # We copy this logic from pygame upstream, because reasons
            theta = -90.0 * theta / pi
            return theta
        return 0.0

    def centroid(self):
        """centroid() -> (x, y)

           Returns the centroid of the pixels in a Mask"""
        xs = ys = tot = 0
        for x in range(self._mask.w):
            for y in range(self._mask.h):
                if sdl.bitmask_getbit(self._mask, x, y):
                    ys += y
                    xs += x
                    tot += 1
        if tot:
            return (xs // tot, ys // tot)
        return (0, 0)

    def clear(self):
        """clear() -> None

           Sets all bits to 0"""
        sdl.bitmask_clear(self._mask)

    def connected_component(self, pos=None):
        """connected_component((x,y) = None) -> Mask

            Returns a mask of a connected region of pixels."""
        output = Mask((self._mask.w, self._mask.h))
        # if a coordinate is specified, make the pixel there is actually set
        x = y = -1
        check = True
        if pos:
            x, y = pos
            if not sdl.bitmask_getbit(self._mask, x, y):
                check = False
        if check:
            r = sdl.largest_connected_comp(self._mask, output._mask, x, y)
            if r == -2:
                raise MemoryError("Not enough memory to get largest component")
        return output

    def connected_components(self, min=0):
        """connected_components(min = 0) -> [Masks]

           Returns a list of masks of connected regions of pixels."""
        components = ffi.new('bitmask_t***')
        num_components = sdl.get_connected_components(self._mask, components,
                                                      min)
        if num_components == -2:
            raise MemoryError("Not enough memory to get components.")
        ret = []
        # Array is indexed from 1
        for i in range(1, num_components + 1):
            m = Mask((1, 1))
            sdl.bitmask_free(m._mask)
            m._mask = components[0][i]
            ret.append(m)
        return ret

    def convolve(self, othermask, outputmask=None, offset=(0, 0)):
        """convolve(othermask, outputmask = None, offset = (0,0)) -> Mask

           Return the convolution of self with another mask."""
        a = self._mask
        b = othermask._mask
        if outputmask is None:
            outputmask = Mask((a.w + b.w - 1, a.h + b.h - 1))
        sdl.bitmask_convolve(a, b, outputmask._mask, offset[0], offset[1])
        return outputmask

    def count(self):
        """count() -> pixels

           Returns the number of set pixels"""
        return int(sdl.bitmask_count(self._mask))

    def draw(self, othermask, offset):
        """draw(othermask, offset) -> None

           Draws a mask onto another"""
        sdl.bitmask_draw(self._mask, othermask._mask, offset[0],
                         offset[1])

    def erase(self, othermask, offset):
        """erase(othermask, offset) -> None

           Erases a mask from another"""
        sdl.bitmask_erase(self._mask, othermask._mask, offset[0],
                          offset[1])

    def fill(self):
        """fill() -> None

           Sets all bits to 1"""
        sdl.bitmask_fill(self._mask)

    def get_at(self, pos):
        """get_at((x,y)) -> int

           Returns nonzero if the bit at (x,y) is set."""
        x, y = pos
        if 0 <= x < self._mask.w and 0 <= y < self._mask.h:
            val = sdl.bitmask_getbit(self._mask, x, y)
        else:
            raise IndexError("%d, %d out of bounds" % pos)
        return val

    def get_bounding_rects(self):
        """get_bounding_rects() -> Rects

           Returns a list of bounding rects of regions of set pixels."""
        num_bounding_boxes = ffi.new('int[1]')
        regions = ffi.new('SDL_Rect**')
        r = sdl.internal_get_bounding_rects(self._mask,
                                            num_bounding_boxes, regions)
        if r == -2:
            raise MemoryError("Not enough memory to get bounding rects.")
        rects = []
        # The C code creates an array indexed from 1.
        # This turns out to be surprisingly hard to figure out.
        for i in range(1, num_bounding_boxes[0] + 1):
            region = regions[0][i]
            rects.append(Rect((region.x, region.y,
                               region.w, region.h)))
        return rects

    def get_size(self):
        """get_size() -> width,height

           Returns the size of the mask."""
        return self._mask.w, self._mask.h

    def invert(self):
        """invert() -> None

           Flips the bits in a Mask"""
        sdl.bitmask_invert(self._mask)

    def outline(self, every=1):
        """outline(every = 1) -> [(x,y), (x,y) ...]

           list of points outlining an object"""
        # Find the first set pixel in the mask
        points = []
        start_point = None
        for y in range(self._mask.h):
            for x in range(self._mask.w):
                if sdl.bitmask_getbit(self._mask, x, y):
                    # We add 1 because of later padding trick
                    start_point = x + 1, y + 1
                    points.append((x, y))
                    break
            if points:
                break
        # If not pixels, break out
        if not points:
            return points
        # Check for corner case around only last pixel being set
        if start_point == (self._mask.w, self._mask.h):
            return points
        # We create a larger mask, to avoid checking edges for every pixel
        trace = Mask((self._mask.w + 2, self._mask.h + 2))
        sdl.bitmask_draw(trace._mask, self._mask, 1, 1)

        # This walks around a pixel clockwise.
        # We have doubled this for the logic later
        offsets = [(1, 0), (1, 1), (0, 1), (-1, 1),
                   (-1, 0), (-1, -1), (0, -1), (1, -1)] * 2
        curr = second = None
        pos = 0
        # We check just the first point for neighbours
        for p, off in enumerate(offsets[:8]):
            cand = (start_point[0] + off[0], start_point[1] + off[1])
            if sdl.bitmask_getbit(trace._mask, cand[0], cand[1]):
                curr = second = cand
                # Scale back to our mask
                points.append((second[0] - 1, second[1] - 1))
                # Set appropriate start point for next loop
                pos = p + 5
                break
        if not second:
            # No neighbours
            return points

        # Trace the outline
        next_point = curr
        while True:
            for p, off in enumerate(offsets[pos:pos + 8]):
                cand = (curr[0] + off[0], curr[1] + off[1])
                if sdl.bitmask_getbit(trace._mask, cand[0], cand[1]):
                    # The logic here is a little hairy, but we must
                    # make sure we test all other neighbors before we
                    # test going from next_point back to curr_point
                    # For example, if we found next_point using (1, 1)
                    # we need to test (-1, -1) last when checking next_point.
                    pos = (pos + p + 5) % 8
                    next_point = cand
                    if curr != start_point or next_point != second:
                        # Not yet back at the start
                        points.append((next_point[0] - 1, next_point[1] - 1))
                    break
            if curr == start_point and next_point == second:
                # About to repeat ourselves, so we're done
                break
            curr = next_point

        # Return asked for subset of points
        return points[::every]

    def overlap(self, othermask, offset):
        """overlap(othermask, offset) -> x,y

           Returns the point of intersection if the masks overlap with
           the given offset - or None if it does not overlap."""
        x, y = offset
        xp = ffi.new('int[1]')
        yp = ffi.new('int[1]')
        val = sdl.bitmask_overlap_pos(self._mask, othermask._mask,
                                      x, y, xp, yp)
        if val:
            return (xp[0], yp[0])
        return None

    def overlap_area(self, othermask, offset):
        """overlap_area(othermask, offset) -> numpixels

           Returns the number of overlapping 'pixels'."""
        x, y = offset
        val = sdl.bitmask_overlap_area(self._mask, othermask._mask, x, y)
        return val

    def overlap_mask(self, othermask, offset):
        """overlap_mask(othermask, offset) -> Mask

            Returns a mask of the overlapping pixels"""
        x, y = offset
        output = Mask((self._mask.w, self._mask.h))
        sdl.bitmask_overlap_mask(self._mask, othermask._mask,
                                 output._mask, x, y)
        return output

    def scale(self, new_size):
        """scale((x, y)) -> Mask

            Resizes a mask"""
        output = Mask(new_size)
        output._mask = sdl.bitmask_scale(self._mask, new_size[0], new_size[1])
        return output

    def set_at(self, pos, value=1):
        """set_at((x,y), value=1) -> None

           Sets the position in the mask given by x and y."""
        x, y = pos
        if 0 <= x < self._mask.w and 0 <= y < self._mask.h:
            if value:
                sdl.bitmask_setbit(self._mask, x, y)
            else:
                sdl.bitmask_clearbit(self._mask, x, y)
        else:
            raise IndexError("%d, %d out of bounds" % pos)

def from_surface(surf, threshold=127):
    """from_surface(surf, threshold = 127) -> Mask

       Returns a Mask from the given surface"""
    c_surf = surf._c_surface
    output_mask = Mask((surf._w, surf._h))
    # colorkey will be None if we're not using a colorkey
    colorkey = surf.get_colorkey()
    format = surf._c_surface.format
    r, g, b, a = (ffi.new('uint8_t *'), ffi.new('uint8_t *'),
                  ffi.new('uint8_t *'), ffi.new('uint8_t *'))
    with locked(c_surf):
        for y in range(surf._h):
            for x in range(surf._w):
                sdl.SDL_GetRGBA(surf._get_at(x, y), format, r, g, b, a)
                if colorkey is None:
                    # check alpha
                    if a[0] > threshold:
                        sdl.bitmask_setbit(output_mask._mask, x, y)
                else:
                    pixel = (r[0], g[0], b[0], a[0])
                    if pixel == colorkey:
                        sdl.bitmask_setbit(output_mask._mask, x, y)
    return output_mask

def from_threshold(surf, color, threshold=(0, 0, 0, 255), othersurface=None,
                   palette_colors=1):
    """from_threshold(surf, color, threshold = (0,0,0,255), othersurface = None,
                      palette_colors = 1) -> Mask

        Creates a mask by thresholding Surfaces"""
    c_surf = surf._c_surface
    color = create_color(color, surf._c_surface.format)
    if threshold:
        threshold = create_color(threshold, c_surf.format)

    output_mask = Mask((surf._w, surf._h))

    with locked(c_surf):
        if othersurface:
            surf2 = othersurface._c_surface
            with locked(surf2):
                sdl.bitmask_threshold(output_mask._mask, c_surf, surf2, color,
                                      threshold, palette_colors)
        else:
            sdl.bitmask_threshold(output_mask._mask, c_surf, ffi.NULL, color,
                                  threshold, palette_colors)
    return output_mask
<commit_msg>Fix comment<commit_after># Implement the pygame API for the bitmask functions

from math import atan2, pi

from pygame._sdl import sdl, ffi
from pygame.surflock import locked
from pygame.rect import Rect
from pygame.color import create_color

class Mask(object):
    """pygame.Mask((width, height)): return Mask

       pygame object for representing 2d bitmask"""

    def __init__(self, size):
        self._mask = sdl.bitmask_create(size[0], size[1])

    def __del__(self):
        if self._mask:
            sdl.bitmask_free(self._mask)

    def angle(self):
        """angle() -> theta

           Returns the orientation of the pixels"""
        xs = ys = tot = 0
        # multiplication counters
        xx = yy = xy = 0
        for x in range(self._mask.w):
            for y in range(self._mask.h):
                if sdl.bitmask_getbit(self._mask, x, y):
                    ys += y
                    xs += x
                    tot += 1
                    xx += x * x
                    yy += y * y
                    xy += x * y
        if tot:
            xc = xs // tot
            yc = ys // tot
            theta = atan2(2 * (xy / tot - xc * yc),
                          (xx / tot - xc * xc) - (yy / tot - yc * yc))
            # covert from radians
            # We copy this logic from pygame upstream, because reasons
            theta = -90.0 * theta / pi
            return theta
        return 0.0

    def centroid(self):
        """centroid() -> (x, y)

           Returns the centroid of the pixels in a Mask"""
        xs = ys = tot = 0
        for x in range(self._mask.w):
            for y in range(self._mask.h):
                if sdl.bitmask_getbit(self._mask, x, y):
                    ys += y
                    xs += x
                    tot += 1
        if tot:
            return (xs // tot, ys // tot)
        return (0, 0)

    def clear(self):
        """clear() -> None

           Sets all bits to 0"""
        sdl.bitmask_clear(self._mask)

    def connected_component(self, pos=None):
        """connected_component((x,y) = None) -> Mask

            Returns a mask of a connected region of pixels."""
        output = Mask((self._mask.w, self._mask.h))
        # if a coordinate is specified, make sure the pixel there is
        # actually set
        x = y = -1
        check = True
        if pos:
            x, y = pos
            if not sdl.bitmask_getbit(self._mask, x, y):
                check = False
        if check:
            r = sdl.largest_connected_comp(self._mask, output._mask, x, y)
            if r == -2:
                raise MemoryError("Not enough memory to get largest component")
        return output

    def connected_components(self, min=0):
        """connected_components(min = 0) -> [Masks]

           Returns a list of masks of connected regions of pixels."""
        components = ffi.new('bitmask_t***')
        num_components = sdl.get_connected_components(self._mask, components,
                                                      min)
        if num_components == -2:
            raise MemoryError("Not enough memory to get components.")
        ret = []
        # Array is indexed from 1
        for i in range(1, num_components + 1):
            m = Mask((1, 1))
            sdl.bitmask_free(m._mask)
            m._mask = components[0][i]
            ret.append(m)
        return ret

    def convolve(self, othermask, outputmask=None, offset=(0, 0)):
        """convolve(othermask, outputmask = None, offset = (0,0)) -> Mask

           Return the convolution of self with another mask."""
        a = self._mask
        b = othermask._mask
        if outputmask is None:
            outputmask = Mask((a.w + b.w - 1, a.h + b.h - 1))
        sdl.bitmask_convolve(a, b, outputmask._mask, offset[0], offset[1])
        return outputmask

    def count(self):
        """count() -> pixels

           Returns the number of set pixels"""
        return int(sdl.bitmask_count(self._mask))

    def draw(self, othermask, offset):
        """draw(othermask, offset) -> None

           Draws a mask onto another"""
        sdl.bitmask_draw(self._mask, othermask._mask, offset[0],
                         offset[1])

    def erase(self, othermask, offset):
        """erase(othermask, offset) -> None

           Erases a mask from another"""
        sdl.bitmask_erase(self._mask, othermask._mask, offset[0],
                          offset[1])

    def fill(self):
        """fill() -> None

           Sets all bits to 1"""
        sdl.bitmask_fill(self._mask)

    def get_at(self, pos):
        """get_at((x,y)) -> int

           Returns nonzero if the bit at (x,y) is set."""
        x, y = pos
        if 0 <= x < self._mask.w and 0 <= y < self._mask.h:
            val = sdl.bitmask_getbit(self._mask, x, y)
        else:
            raise IndexError("%d, %d out of bounds" % pos)
        return val

    def get_bounding_rects(self):
        """get_bounding_rects() -> Rects

           Returns a list of bounding rects of regions of set pixels."""
        num_bounding_boxes = ffi.new('int[1]')
        regions = ffi.new('SDL_Rect**')
        r = sdl.internal_get_bounding_rects(self._mask,
                                            num_bounding_boxes, regions)
        if r == -2:
            raise MemoryError("Not enough memory to get bounding rects.")
        rects = []
        # The C code creates an array indexed from 1.
        # This turns out to be surprisingly hard to figure out.
        for i in range(1, num_bounding_boxes[0] + 1):
            region = regions[0][i]
            rects.append(Rect((region.x, region.y,
                               region.w, region.h)))
        return rects

    def get_size(self):
        """get_size() -> width,height

           Returns the size of the mask."""
        return self._mask.w, self._mask.h

    def invert(self):
        """invert() -> None

           Flips the bits in a Mask"""
        sdl.bitmask_invert(self._mask)

    def outline(self, every=1):
        """outline(every = 1) -> [(x,y), (x,y) ...]

           list of points outlining an object"""
        # Find the first set pixel in the mask
        points = []
        start_point = None
        for y in range(self._mask.h):
            for x in range(self._mask.w):
                if sdl.bitmask_getbit(self._mask, x, y):
                    # We add 1 because of later padding trick
                    start_point = x + 1, y + 1
                    points.append((x, y))
                    break
            if points:
                break
        # If not pixels, break out
        if not points:
            return points
        # Check for corner case around only last pixel being set
        if start_point == (self._mask.w, self._mask.h):
            return points
        # We create a larger mask, to avoid checking edges for every pixel
        trace = Mask((self._mask.w + 2, self._mask.h + 2))
        sdl.bitmask_draw(trace._mask, self._mask, 1, 1)

        # This walks around a pixel clockwise.
        # We have doubled this for the logic later
        offsets = [(1, 0), (1, 1), (0, 1), (-1, 1),
                   (-1, 0), (-1, -1), (0, -1), (1, -1)] * 2
        curr = second = None
        pos = 0
        # We check just the first point for neighbours
        for p, off in enumerate(offsets[:8]):
            cand = (start_point[0] + off[0], start_point[1] + off[1])
            if sdl.bitmask_getbit(trace._mask, cand[0], cand[1]):
                curr = second = cand
                # Scale back to our mask
                points.append((second[0] - 1, second[1] - 1))
                # Set appropriate start point for next loop
                pos = p + 5
                break
        if not second:
            # No neighbours
            return points

        # Trace the outline
        next_point = curr
        while True:
            for p, off in enumerate(offsets[pos:pos + 8]):
                cand = (curr[0] + off[0], curr[1] + off[1])
                if sdl.bitmask_getbit(trace._mask, cand[0], cand[1]):
                    # The logic here is a little hairy, but we must
                    # make sure we test all other neighbors before we
                    # test going from next_point back to curr_point
                    # For example, if we found next_point using (1, 1)
                    # we need to test (-1, -1) last when checking next_point.
                    pos = (pos + p + 5) % 8
                    next_point = cand
                    if curr != start_point or next_point != second:
                        # Not yet back at the start
                        points.append((next_point[0] - 1, next_point[1] - 1))
                    break
            if curr == start_point and next_point == second:
                # About to repeat ourselves, so we're done
                break
            curr = next_point

        # Return asked for subset of points
        return points[::every]

    def overlap(self, othermask, offset):
        """overlap(othermask, offset) -> x,y

           Returns the point of intersection if the masks overlap with
           the given offset - or None if it does not overlap."""
        x, y = offset
        xp = ffi.new('int[1]')
        yp = ffi.new('int[1]')
        val = sdl.bitmask_overlap_pos(self._mask, othermask._mask,
                                      x, y, xp, yp)
        if val:
            return (xp[0], yp[0])
        return None

    def overlap_area(self, othermask, offset):
        """overlap_area(othermask, offset) -> numpixels

           Returns the number of overlapping 'pixels'."""
        x, y = offset
        val = sdl.bitmask_overlap_area(self._mask, othermask._mask, x, y)
        return val

    def overlap_mask(self, othermask, offset):
        """overlap_mask(othermask, offset) -> Mask

            Returns a mask of the overlapping pixels"""
        x, y = offset
        output = Mask((self._mask.w, self._mask.h))
        sdl.bitmask_overlap_mask(self._mask, othermask._mask,
                                 output._mask, x, y)
        return output

    def scale(self, new_size):
        """scale((x, y)) -> Mask

            Resizes a mask"""
        output = Mask(new_size)
        output._mask = sdl.bitmask_scale(self._mask, new_size[0], new_size[1])
        return output

    def set_at(self, pos, value=1):
        """set_at((x,y), value=1) -> None

           Sets the position in the mask given by x and y."""
        x, y = pos
        if 0 <= x < self._mask.w and 0 <= y < self._mask.h:
            if value:
                sdl.bitmask_setbit(self._mask, x, y)
            else:
                sdl.bitmask_clearbit(self._mask, x, y)
        else:
            raise IndexError("%d, %d out of bounds" % pos)

def from_surface(surf, threshold=127):
    """from_surface(surf, threshold = 127) -> Mask

       Returns a Mask from the given surface"""
    c_surf = surf._c_surface
    output_mask = Mask((surf._w, surf._h))
    # colorkey will be None if we're not using a colorkey
    colorkey = surf.get_colorkey()
    format = surf._c_surface.format
    r, g, b, a = (ffi.new('uint8_t *'), ffi.new('uint8_t *'),
                  ffi.new('uint8_t *'), ffi.new('uint8_t *'))
    with locked(c_surf):
        for y in range(surf._h):
            for x in range(surf._w):
                sdl.SDL_GetRGBA(surf._get_at(x, y), format, r, g, b, a)
                if colorkey is None:
                    # check alpha
                    if a[0] > threshold:
                        sdl.bitmask_setbit(output_mask._mask, x, y)
                else:
                    pixel = (r[0], g[0], b[0], a[0])
                    if pixel == colorkey:
                        sdl.bitmask_setbit(output_mask._mask, x, y)
    return output_mask

def from_threshold(surf, color, threshold=(0, 0, 0, 255), othersurface=None,
                   palette_colors=1):
    """from_threshold(surf, color, threshold = (0,0,0,255), othersurface = None,
                      palette_colors = 1) -> Mask

        Creates a mask by thresholding Surfaces"""
    c_surf = surf._c_surface
    color = create_color(color, surf._c_surface.format)
    if threshold:
        threshold = create_color(threshold, c_surf.format)

    output_mask = Mask((surf._w, surf._h))

    with locked(c_surf):
        if othersurface:
            surf2 = othersurface._c_surface
            with locked(surf2):
                sdl.bitmask_threshold(output_mask._mask, c_surf, surf2, color,
                                      threshold, palette_colors)
        else:
            sdl.bitmask_threshold(output_mask._mask, c_surf, ffi.NULL, color,
                                  threshold, palette_colors)
    return output_mask
<|endoftext|>


<commit_before>import os
import platform
import shutil
import subprocess
from distutils import dir_util

from conans import __version__
from conans.util.files import save

def _install_pyinstaller(pyinstaller_path):
    subprocess.call("pip install pyinstaller", shell=True)
    # try to install pyinstaller if not installed
    if not os.path.exists(pyinstaller_path):
        os.mkdir(pyinstaller_path)

def _run_bin(pyinstaller_path):
    # run the binary to test if working
    conan_bin = os.path.join(pyinstaller_path, 'dist', 'conan', 'conan')
    if platform.system() == 'Windows':
        conan_bin = '"' + conan_bin + '.exe' + '"'
    retcode = os.system(conan_bin)
    if retcode != 0:
        raise Exception("Binary not working")

def _windows_version_file(version):
    template = """# UTF-8
#
# For more details about fixed file info 'ffi' see:
# http://msdn.microsoft.com/en-us/library/ms646997.aspx
VSVersionInfo(
  ffi=FixedFileInfo(
    # filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4)
    # Set not needed items to zero 0.
    filevers={version_tuple},
    prodvers={version_tuple},
    # Contains a bitmask that specifies the valid bits 'flags'r
    mask=0x3f,
    # Contains a bitmask that specifies the Boolean attributes of the file.
    flags=0x0,
    # The operating system for which this file was designed.
    # 0x4 - NT and there is no need to change it.
    OS=0x4,
    # The general type of file.
    # 0x1 - the file is an application.
    fileType=0x1,
    # The function of the file.
    # 0x0 - the function is not defined for this fileType
    subtype=0x0,
    # Creation date and time stamp.
    date=(0, 0)
    ),
  kids=[
    StringFileInfo(
      [
      StringTable(
        u'000004b0',
        [StringStruct(u'Comments', u'This executable was created with pyinstaller'),
        StringStruct(u'CompanyName', u'JFrog'),
        StringStruct(u'FileDescription', u'Conan C, C++ Open Source Package Manager'),
        StringStruct(u'FileVersion', u'{version}'),
        StringStruct(u'LegalCopyright', u'Copyright 2020 JFrog'),
        StringStruct(u'ProductName', u'Conan'),
        StringStruct(u'ProductVersion', u'{version}')])
      ]),
    VarFileInfo([VarStruct(u'Translation', [0, 1200])])
  ]
)"""
    if "-" in version:
        version, _ = version.split("-")
    version_tuple = tuple([int(v) for v in version.split(".")] + [0])
    return template.format(version=version, version_tuple=version_tuple)

def pyinstall(source_folder):
    pyinstaller_path = os.path.join(os.getcwd(), 'pyinstaller')
    _install_pyinstaller(pyinstaller_path)
    command = "pyinstaller"  # "python pyinstaller.py"

    try:
        shutil.rmtree(os.path.join(pyinstaller_path))
    except Exception as e:
        print("Unable to remove old folder", e)

    conan_path = os.path.join(source_folder, 'conans', 'conan.py')
    conan_server_path = os.path.join(source_folder, 'conans', 'conan_server.py')
    conan_build_info_path = os.path.join(source_folder, "conans/build_info/command.py")
    hidden = ("--hidden-import=glob --hidden-import=conan.tools.microsoft "
              "--hidden-import=conan.tools.gnu --hidden-import=conan.tools.cmake "
              "--hidden-import=conan.tools.meson")
    if platform.system() != "Windows":
        hidden += " --hidden-import=setuptools.msvc"
        win_ver = ""
    else:
        win_ver_file = os.path.join(pyinstaller_path, 'windows-version-file')
        content = _windows_version_file(__version__)
        save(win_ver_file, content)
        win_ver = "--version-file \"%s\"" % win_ver_file

    if not os.path.exists(pyinstaller_path):
        os.mkdir(pyinstaller_path)
    subprocess.call('%s -y -p "%s" --console "%s" %s %s'
                    % (command, source_folder, conan_path, hidden, win_ver),
                    cwd=pyinstaller_path, shell=True)

    _run_bin(pyinstaller_path)

    subprocess.call('%s -y -p "%s" --console "%s" %s'
                    % (command, source_folder, conan_server_path, win_ver),
                    cwd=pyinstaller_path, shell=True)

    subprocess.call('%s -y -p "%s" --console "%s" -n conan_build_info %s'
                    % (command, source_folder, conan_build_info_path, win_ver),
                    cwd=pyinstaller_path, shell=True)

    conan_bin = os.path.join(pyinstaller_path, 'dist', 'conan')
    conan_server_folder = os.path.join(pyinstaller_path, 'dist', 'conan_server')

    conan_build_info_folder = os.path.join(pyinstaller_path, 'dist', 'conan_build_info')
    dir_util.copy_tree(conan_server_folder, conan_bin)
    dir_util.copy_tree(conan_build_info_folder, conan_bin)
    _run_bin(pyinstaller_path)

    return os.path.abspath(os.path.join(pyinstaller_path, 'dist', 'conan'))

if __name__ == "__main__":
    src_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
    output_folder = pyinstall(src_folder)
    print("\n**************Conan binaries created!******************\n"
          "\nAppend this folder to your system PATH: '%s'\n"
          "Feel free to move the whole folder to another location." % output_folder)
<commit_msg>adding hidden-imports to pyinstaller (#10320)<commit_after>import os
import platform
import shutil
import subprocess
from distutils import dir_util

from conans import __version__
from conans.util.files import save

def _install_pyinstaller(pyinstaller_path):
    subprocess.call("pip install pyinstaller", shell=True)
    # try to install pyinstaller if not installed
    if not os.path.exists(pyinstaller_path):
        os.mkdir(pyinstaller_path)

def _run_bin(pyinstaller_path):
    # run the binary to test if working
    conan_bin = os.path.join(pyinstaller_path, 'dist', 'conan', 'conan')
    if platform.system() == 'Windows':
        conan_bin = '"' + conan_bin + '.exe' + '"'
    retcode = os.system(conan_bin)
    if retcode != 0:
        raise Exception("Binary not working")

def _windows_version_file(version):
    template = """# UTF-8
#
# For more details about fixed file info 'ffi' see:
# http://msdn.microsoft.com/en-us/library/ms646997.aspx
VSVersionInfo(
  ffi=FixedFileInfo(
    # filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4)
    # Set not needed items to zero 0.
    filevers={version_tuple},
    prodvers={version_tuple},
    # Contains a bitmask that specifies the valid bits 'flags'r
    mask=0x3f,
    # Contains a bitmask that specifies the Boolean attributes of the file.
    flags=0x0,
    # The operating system for which this file was designed.
    # 0x4 - NT and there is no need to change it.
    OS=0x4,
    # The general type of file.
    # 0x1 - the file is an application.
    fileType=0x1,
    # The function of the file.
    # 0x0 - the function is not defined for this fileType
    subtype=0x0,
    # Creation date and time stamp.
    date=(0, 0)
    ),
  kids=[
    StringFileInfo(
      [
      StringTable(
        u'000004b0',
        [StringStruct(u'Comments', u'This executable was created with pyinstaller'),
        StringStruct(u'CompanyName', u'JFrog'),
        StringStruct(u'FileDescription', u'Conan C, C++ Open Source Package Manager'),
        StringStruct(u'FileVersion', u'{version}'),
        StringStruct(u'LegalCopyright', u'Copyright 2020 JFrog'),
        StringStruct(u'ProductName', u'Conan'),
        StringStruct(u'ProductVersion', u'{version}')])
      ]),
    VarFileInfo([VarStruct(u'Translation', [0, 1200])])
  ]
)"""
    if "-" in version:
        version, _ = version.split("-")
    version_tuple = tuple([int(v) for v in version.split(".")] + [0])
    return template.format(version=version, version_tuple=version_tuple)

def pyinstall(source_folder):
    pyinstaller_path = os.path.join(os.getcwd(), 'pyinstaller')
    _install_pyinstaller(pyinstaller_path)
    command = "pyinstaller"  # "python pyinstaller.py"

    try:
        shutil.rmtree(os.path.join(pyinstaller_path))
    except Exception as e:
        print("Unable to remove old folder", e)

    conan_path = os.path.join(source_folder, 'conans', 'conan.py')
    conan_server_path = os.path.join(source_folder, 'conans', 'conan_server.py')
    conan_build_info_path = os.path.join(source_folder, "conans/build_info/command.py")
    hidden = ("--hidden-import=glob --hidden-import=conan.tools.microsoft "
              "--hidden-import=conan.tools.gnu --hidden-import=conan.tools.cmake "
              "--hidden-import=conan.tools.meson --hidden-import=conan.tools.apple "
              "--hidden-import=conan.tools.build --hidden-import=conan.tools.env "
              "--hidden-import=conan.tools.files --hidden-import=conan.tools.gnu "
              "--hidden-import=conan.tools.google --hidden-import=conan.tools.intel "
              "--hidden-import=conan.tools.layout --hidden-import=conan.tools.premake "
              "--hidden-import=conan.tools.qbs")
    hidden += " --hidden-import=distutils.dir_util"
    if platform.system() != "Windows":
        hidden += " --hidden-import=setuptools.msvc"
        win_ver = ""
    else:
        win_ver_file = os.path.join(pyinstaller_path, 'windows-version-file')
        content = _windows_version_file(__version__)
        save(win_ver_file, content)
        win_ver = "--version-file \"%s\"" % win_ver_file

    if not os.path.exists(pyinstaller_path):
        os.mkdir(pyinstaller_path)
    subprocess.call('%s -y -p "%s" --console "%s" %s %s'
                    % (command, source_folder, conan_path, hidden, win_ver),
                    cwd=pyinstaller_path, shell=True)

    _run_bin(pyinstaller_path)

    subprocess.call('%s -y -p "%s" --console "%s" %s'
                    % (command, source_folder, conan_server_path, win_ver),
                    cwd=pyinstaller_path, shell=True)

    subprocess.call('%s -y -p "%s" --console "%s" -n conan_build_info %s'
                    % (command, source_folder, conan_build_info_path, win_ver),
                    cwd=pyinstaller_path, shell=True)

    conan_bin = os.path.join(pyinstaller_path, 'dist', 'conan')
    conan_server_folder = os.path.join(pyinstaller_path, 'dist', 'conan_server')

    conan_build_info_folder = os.path.join(pyinstaller_path, 'dist', 'conan_build_info')
    dir_util.copy_tree(conan_server_folder, conan_bin)
    dir_util.copy_tree(conan_build_info_folder, conan_bin)
    _run_bin(pyinstaller_path)

    return os.path.abspath(os.path.join(pyinstaller_path, 'dist', 'conan'))

if __name__ == "__main__":
    src_folder = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
    output_folder = pyinstall(src_folder)
    print("\n**************Conan binaries created!******************\n"
          "\nAppend this folder to your system PATH: '%s'\n"
          "Feel free to move the whole folder to another location." % output_folder)
<|endoftext|>


<commit_before>import lcdui

class KegUI(lcdui.lcdui):
   def __init__(self, device, kb):
      self.kb = kb
      lcdui.lcdui.__init__(self, device)
      self.plate_main = plate_kegbot_main(self)
      self.plate_pour = plate_kegbot_pour(self)

   def startPour(self, user):
      self.kb.handleDrinker(user.getName())

class plate_kegbot_main(lcdui.plate_multi):
   def __init__(self, owner):
      lcdui.plate_multi.__init__(self,owner)
      self.owner = owner

      self.maininfo    = lcdui.plate_std(owner)
      self.tempinfo    = lcdui.plate_std(owner)
      self.freezerinfo = lcdui.plate_std(owner)
      self.lastinfo    = lcdui.plate_std(owner)
      self.drinker     = lcdui.plate_std(owner)
      self.drinkers    = plate_kegbot_drinker_menu(owner, header = "select drinker", default_ptr = self.owner.startPour)

      self.main_menu = lcdui.plate_select_menu(owner,header="kegbot menu")
      self.main_menu.insert(("pour a drink",owner.setCurrentPlate,(self.drinkers,)))
      self.main_menu.insert(("show history",None,()))
      self.main_menu.insert(("add user",None,()))
      self.main_menu.insert(("squelch user",None,()))
      self.main_menu.insert(("lock kegbot",None,()))
      #self.main_menu.insert(("exit",owner.setCurrentPlate,(self,)))

      self.cmd_dict = {'right': (self.owner.setCurrentPlate,(self.main_menu,)) }

      line1 = lcdui.widget_line_std(" ================== ",row=0,col=0,scroll=0)
      line2 = lcdui.widget_line_std("      kegbot!!      ",row=1,col=0,scroll=0)
      line3 = lcdui.widget_line_std("  have good beer!!  ",row=2,col=0,scroll=0)
      line4 = lcdui.widget_line_std(" ================== ",row=3,col=0,scroll=0)

      self.maininfo.updateObject('line1',line1)
      self.maininfo.updateObject('line2',line2)
      self.maininfo.updateObject('line3',line3)
      self.maininfo.updateObject('line4',line4)

      line1 = lcdui.widget_line_std("*------------------*",row=0,col=0,scroll=0)
      line2 = lcdui.widget_line_std("| current temp:    |",row=1,col=0,scroll=0)
      line3 = lcdui.widget_line_std("| unknown          |",row=2,col=0,scroll=0)
      line4 = lcdui.widget_line_std("*------------------*",row=3,col=0,scroll=0)

      self.tempinfo.updateObject('line1',line1)
      self.tempinfo.updateObject('line2',line2)
      self.tempinfo.updateObject('line3',line3)
      self.tempinfo.updateObject('line4',line4)

      line1 = lcdui.widget_line_std("*------------------*",row=0,col=0,scroll=0)
      line2 = lcdui.widget_line_std("| freezer status:  |",row=1,col=0,scroll=0)
      line3 = lcdui.widget_line_std("| [off]            |",row=2,col=0,scroll=0)
      line4 = lcdui.widget_line_std("*------------------*",row=3,col=0,scroll=0)

      self.freezerinfo.updateObject('line1',line1)
      self.freezerinfo.updateObject('line2',line2)
      self.freezerinfo.updateObject('line3',line3)
      self.freezerinfo.updateObject('line4',line4)

      line1 = lcdui.widget_line_std("*------------------*",row=0,col=0,scroll=0)
      line2 = lcdui.widget_line_std("| last pour:       |",row=1,col=0,scroll=0)
      line3 = lcdui.widget_line_std("| 0.0 oz           |",row=2,col=0,scroll=0)
      line4 = lcdui.widget_line_std("*------------------*",row=3,col=0,scroll=0)

      self.lastinfo.updateObject('line1',line1)
      self.lastinfo.updateObject('line2',line2)
      self.lastinfo.updateObject('line3',line3)
      self.lastinfo.updateObject('line4',line4)

      line1 = lcdui.widget_line_std("*------------------*",row=0,col=0,scroll=0)
      line2 = lcdui.widget_line_std("| last drinker:    |",row=1,col=0,scroll=0)
      line3 = lcdui.widget_line_std("| unknown          |",row=2,col=0,scroll=0)
      line4 = lcdui.widget_line_std("*------------------*",row=3,col=0,scroll=0)

      self.drinker.updateObject('line1',line1)
      self.drinker.updateObject('line2',line2)
      self.drinker.updateObject('line3',line3)
      self.drinker.updateObject('line4',line4)

      self.addPlate("main",self.maininfo)
      self.addPlate("temp",self.tempinfo)
      self.addPlate("freezer",self.freezerinfo)
      self.addPlate("last",self.lastinfo)
      self.addPlate("drinker",self.drinker)

      # starts the rotation
      self.rotate_time = 5.0

   def setTemperature(self,tempc):
      inside = "%.1fc/%.1ff" % (tempc,toF(tempc))
      line3 = lcdui.widget_line_std("%s"%inside,row=2,col=0,prefix="| ", postfix= " |", scroll=0)
      self.tempinfo.updateObject('line3',line3)

   def setFreezer(self,status):
      inside = "[%s]" % status
      line3 = lcdui.widget_line_std("%s"%inside,row=2,col=0,prefix="| ", postfix= " |", scroll=0)
      self.freezerinfo.updateObject('line3',line3)

   def setLastDrink(self,user,ounces):
      line3 = lcdui.widget_line_std("%s oz"%ounces,row=2,col=0,prefix ="| ",postfix=" |",scroll=0)
      self.lastinfo.updateObject('line3',line3)
      line3 = lcdui.widget_line_std("%s"%user,row=2,col=0,prefix ="| ",postfix=" |",scroll=0)
      self.drinker.updateObject('line3',line3)

   def gotKey(self,key):
      lcdui.plate_multi.gotKey(self,key)

class plate_kegbot_pour(lcdui.plate_std):
   def __init__(self, owner):
      lcdui.plate_std.__init__(self,owner)
      self.owner = owner

      self.cmd_dict['enter'] = (self.owner.kb.stopFlow, ())
      self.cmd_dict['exit'] = (self.owner.kb.stopFlow, ())

      line1 = lcdui.widget_line_std("*------------------*", row=0, col=0, scroll=0)
      self.line2 = lcdui.widget_line_std("", row=1, col=0, scroll=0, prefix='| ', postfix=' |')
      self.line3 = lcdui.widget_progbar(row = 2, col = 2, prefix ='[', postfix=']', proglen = 9)
      line4 = lcdui.widget_line_std("*------------------*",row=3,col=0,scroll=0)

      pipe1 = lcdui.widget_line_std("|", row=2,col=0,scroll=0,fat=0)
      pipe2 = lcdui.widget_line_std("|", row=2,col=19,scroll=0,fat=0)
      ounces = lcdui.widget_line_std("", row=2,col=12,scroll=0,fat=0)

      self.updateObject('line1',line1)
      self.updateObject('line2',self.line2)
      self.updateObject('progbar',self.line3)
      self.updateObject('line4',line4)
      self.updateObject('pipe1',pipe1)
      self.updateObject('pipe2',pipe2)
      self.updateObject('ounces',ounces)

   def setDrinker(self, name):
      self.line2.setData('hello, ' + name)

class plate_kegbot_drinker_menu(lcdui.plate_select_menu):
   def onSwitchIn(self):
      users = self.owner.kb.user_store.getAllUsers()
      if self.cursor + self.offset >= users:
         self.reset()
      self.menu = []
      for u in users:
         self.menu.append((u.getName(), self.owner.startPour, (u,)))
      self.refreshMenu()

<commit_msg>added standby functions<commit_after>import lcdui

class KegUI(lcdui.lcdui):
   def __init__(self, device, kb):
      self.kb = kb
      lcdui.lcdui.__init__(self, device)
      self.plate_standby = plate_kegbot_standby(self)
      self.plate_main = plate_kegbot_main(self)
      self.plate_pour = plate_kegbot_pour(self)

   def startPour(self, user):
      self.kb.handleDrinker(user.getName())

class plate_kegbot_main(lcdui.plate_multi):
   def __init__(self, owner):
      lcdui.plate_multi.__init__(self,owner)
      self.owner = owner

      self.maininfo    = lcdui.plate_std(owner)
      self.tempinfo    = lcdui.plate_std(owner)
      self.freezerinfo = lcdui.plate_std(owner)
      self.lastinfo    = lcdui.plate_std(owner)
      self.drinker     = lcdui.plate_std(owner)
      self.drinkers    = plate_kegbot_drinker_menu(owner, header = "select drinker", default_ptr = self.owner.startPour)

      self.main_menu = lcdui.plate_select_menu(owner,header="kegbot menu")
      self.main_menu.insert(("pour a drink",owner.setCurrentPlate,(self.drinkers,)))
      self.main_menu.insert(("display standby",owner.setCurrentPlate,(owner.plate_standby,)))
      self.main_menu.insert(("drink cancel",None,()))
      self.main_menu.insert(("add user",None,()))
      self.main_menu.insert(("lock kegbot",None,()))
      #self.main_menu.insert(("exit",owner.setCurrentPlate,(self,)))

      self.cmd_dict = {'right': (self.owner.setCurrentPlate,(self.main_menu,)) }

      line1 = lcdui.widget_line_std(" ================== ",row=0,col=0,scroll=0)
      line2 = lcdui.widget_line_std("      kegbot!!      ",row=1,col=0,scroll=0)
      line3 = lcdui.widget_line_std("  have good beer!!  ",row=2,col=0,scroll=0)
      line4 = lcdui.widget_line_std(" ================== ",row=3,col=0,scroll=0)

      self.maininfo.updateObject('line1',line1)
      self.maininfo.updateObject('line2',line2)
      self.maininfo.updateObject('line3',line3)
      self.maininfo.updateObject('line4',line4)

      line1 = lcdui.widget_line_std("*------------------*",row=0,col=0,scroll=0)
      line2 = lcdui.widget_line_std("| current temp:    |",row=1,col=0,scroll=0)
      line3 = lcdui.widget_line_std("| unknown          |",row=2,col=0,scroll=0)
      line4 = lcdui.widget_line_std("*------------------*",row=3,col=0,scroll=0)

      self.tempinfo.updateObject('line1',line1)
      self.tempinfo.updateObject('line2',line2)
      self.tempinfo.updateObject('line3',line3)
      self.tempinfo.updateObject('line4',line4)

      line1 = lcdui.widget_line_std("*------------------*",row=0,col=0,scroll=0)
      line2 = lcdui.widget_line_std("| freezer status:  |",row=1,col=0,scroll=0)
      line3 = lcdui.widget_line_std("| [off]            |",row=2,col=0,scroll=0)
      line4 = lcdui.widget_line_std("*------------------*",row=3,col=0,scroll=0)

      self.freezerinfo.updateObject('line1',line1)
      self.freezerinfo.updateObject('line2',line2)
      self.freezerinfo.updateObject('line3',line3)
      self.freezerinfo.updateObject('line4',line4)

      line1 = lcdui.widget_line_std("*------------------*",row=0,col=0,scroll=0)
      line2 = lcdui.widget_line_std("| last pour:       |",row=1,col=0,scroll=0)
      line3 = lcdui.widget_line_std("| 0.0 oz           |",row=2,col=0,scroll=0)
      line4 = lcdui.widget_line_std("*------------------*",row=3,col=0,scroll=0)

      self.lastinfo.updateObject('line1',line1)
      self.lastinfo.updateObject('line2',line2)
      self.lastinfo.updateObject('line3',line3)
      self.lastinfo.updateObject('line4',line4)

      line1 = lcdui.widget_line_std("*------------------*",row=0,col=0,scroll=0)
      line2 = lcdui.widget_line_std("| last drinker:    |",row=1,col=0,scroll=0)
      line3 = lcdui.widget_line_std("| unknown          |",row=2,col=0,scroll=0)
      line4 = lcdui.widget_line_std("*------------------*",row=3,col=0,scroll=0)

      self.drinker.updateObject('line1',line1)
      self.drinker.updateObject('line2',line2)
      self.drinker.updateObject('line3',line3)
      self.drinker.updateObject('line4',line4)

      self.addPlate("main",self.maininfo)
      self.addPlate("temp",self.tempinfo)
      self.addPlate("freezer",self.freezerinfo)
      self.addPlate("last",self.lastinfo)
      self.addPlate("drinker",self.drinker)

      # starts the rotation
      self.rotate_time = 5.0

   def setTemperature(self,tempc):
      inside = "%.1fc/%.1ff" % (tempc,toF(tempc))
      line3 = lcdui.widget_line_std("%s"%inside,row=2,col=0,prefix="| ", postfix= " |", scroll=0)
      self.tempinfo.updateObject('line3',line3)

   def setFreezer(self,status):
      inside = "[%s]" % status
      line3 = lcdui.widget_line_std("%s"%inside,row=2,col=0,prefix="| ", postfix= " |", scroll=0)
      self.freezerinfo.updateObject('line3',line3)

   def setLastDrink(self,user,ounces):
      line3 = lcdui.widget_line_std("%s oz"%ounces,row=2,col=0,prefix ="| ",postfix=" |",scroll=0)
      self.lastinfo.updateObject('line3',line3)
      line3 = lcdui.widget_line_std("%s"%user,row=2,col=0,prefix ="| ",postfix=" |",scroll=0)
      self.drinker.updateObject('line3',line3)

   def gotKey(self,key):
      lcdui.plate_multi.gotKey(self,key)

class plate_kegbot_pour(lcdui.plate_std):
   def __init__(self, owner):
      lcdui.plate_std.__init__(self,owner)
      self.owner = owner

      self.cmd_dict['enter'] = (self.owner.kb.stopFlow, ())
      self.cmd_dict['exit'] = (self.owner.kb.stopFlow, ())

      line1 = lcdui.widget_line_std("*------------------*", row=0, col=0, scroll=0)
      self.line2 = lcdui.widget_line_std("", row=1, col=0, scroll=0, prefix='| ', postfix=' |')
      self.line3 = lcdui.widget_progbar(row = 2, col = 2, prefix ='[', postfix=']', proglen = 9)
      line4 = lcdui.widget_line_std("*------------------*",row=3,col=0,scroll=0)

      pipe1 = lcdui.widget_line_std("|", row=2,col=0,scroll=0,fat=0)
      pipe2 = lcdui.widget_line_std("|", row=2,col=19,scroll=0,fat=0)
      ounces = lcdui.widget_line_std("", row=2,col=12,scroll=0,fat=0)

      self.updateObject('line1',line1)
      self.updateObject('line2',self.line2)
      self.updateObject('progbar',self.line3)
      self.updateObject('line4',line4)
      self.updateObject('pipe1',pipe1)
      self.updateObject('pipe2',pipe2)
      self.updateObject('ounces',ounces)

   def setDrinker(self, name):
      self.line2.setData('hello, ' + name)

class plate_kegbot_drinker_menu(lcdui.plate_select_menu):
   def onSwitchIn(self):
      users = self.owner.kb.user_store.getAllUsers()
      if self.cursor + self.offset >= users:
         self.reset()
      self.menu = []
      for u in users:
         self.menu.append((u.getName(), self.owner.startPour, (u,)))
      self.refreshMenu()

class plate_kegbot_standby(lcdui.plate_std):
   def __init__(self, owner):
      lcdui.plate_std.__init__(self, owner)
      self.cmd_dict['up'] = self.owner.backToLastPlate
      self.cmd_dict['down'] = self.owner.backToLastPlate
      self.cmd_dict['left'] = self.owner.backToLastPlate
      self.cmd_dict['right'] = self.owner.backToLastPlate
      self.cmd_dict['enter'] = self.owner.backToLastPlate
      self.cmd_dict['exit'] = self.owner.backToLastPlate

   def onSwitchIn(self):
      self.owner.lcdobj.DisableBacklight()

   def onSwitchOut(self):
      self.owner.lcdobj.EnableBacklight()
<|endoftext|>


<commit_before>"""Paste Template and Pylons utility functions

PylonsTemplate is a Paste Template sub-class that configures the source
directory and default plug-ins for a new Pylons project. The minimal template
provides a more minimal template with less additional directories and layout.
"""
import warnings

from paste.script.appinstall import Installer
from paste.script.templates import Template

import pylons
import pylons.helpers
import pylons.i18n

def func_move(name, moved_to='pylons.i18n'):
    return ("The %s function has moved to %s, please update your import "
            "statements to reflect the move." % (name, moved_to))

def deprecated(func, message):
    def deprecated_method(*args, **kargs):
        warnings.warn(message, DeprecationWarning, 2)
        return func(*args, **kargs)
    try:
        deprecated_method.__name__ = func.__name__
    except TypeError: # Python < 2.4
        pass
    deprecated_method.__doc__ = message + "\n\n" + func.__doc__
    return deprecated_method

get_lang = deprecated(pylons.i18n.get_lang, func_move('get_lang'))
set_lang = deprecated(pylons.i18n.set_lang, func_move('set_lang'))
_ = deprecated(pylons.i18n._, func_move('_'))
log = deprecated(pylons.helpers.log, func_move('log',
                                               moved_to='pylons.helpers'))

def get_prefix(environ):
    if 'paste.config' in environ:
        prefix = environ['paste.config']['app_conf'].get('prefix', '')
    else:
        # Not ideal but if the error occurs before the paste.config is
        # available not a lot we can do
        prefix = ''
    if not prefix:
        if environ.get('SCRIPT_NAME', '') != '':
            prefix = environ['SCRIPT_NAME']
    return prefix

def class_name_from_module_name(module_name):
    """Takes a module name and returns the name of the class it defines.

    If the module name contains dashes, they are replaced with underscores.

    Example::

        >>> class_name_from_module_name('with-dashes')
        'WithDashes'
        >>> class_name_from_module_name('with_underscores')
        'WithUnderscores'
        >>> class_name_from_module_name('oneword')
        'Oneword'
    """
    words = module_name.replace('-', '_').split('_')
    return ''.join([w.title() for w in words])

def config_get(key, default=None):
    """Return a value from ``CONFIG``. Supports both ``paste.config.CONFIG``
    and the older ``paste.deploy.CONFIG``.

    This is for Pylons internal use only; to support both versions of the
    ``CONFIG`` objects, depending on which is used by the current Pylons
    web app."""
    try:
        # environ['paste.config'] is assured to be the correct CONFIG
        # during requests
        CONFIG = pylons.request.environ['paste.config']
        value = CONFIG['app_conf'].get(key, default)
    except TypeError:
        # TypeError: pylons.request isn't registered (this function call was
        # made outside of a web request). fall back to paste.config.CONFIG
        # directly, and finally paste.deploy.CONFIG
        try:
            from paste.config import CONFIG
            value = CONFIG['app_conf'].get(key, default)
        except AttributeError:
            from paste.deploy import CONFIG
            value = CONFIG['app_conf'].get(key, default)
    return value

class ContextObj(object):
    """ The 'c' object, with strict attribute access (raises an Exception when
    the attribute does not exist) """
    pass

class AttribSafeContextObj(object):
    """ The 'c' object, with lax attribute access (returns '' when the
    attribute does not exist) """
    def __getattr__(self, name):
        try:
            return object.__getattribute__(self, name)
        except AttributeError:
            return ''
    def __repr__(self):
        attrs = [(name, value)
                 for name, value in self.__dict__.items()
                 if not name.startswith('_')]
        attrs.sort()
        parts = []
        for name, value in attrs:
            value_repr = repr(value)
            if len(value_repr) > 70:
                value_repr = value_repr[:60] + '...' + value_repr[-5:]
            parts.append('%s=%s' % (name, value_repr))
        return '<%s.%s %s %s>' % (
            self.__class__.__module__,
            self.__class__.__name__,
            hex(id(self)).split('x')[1],
            ' '.join(parts))

class PylonsTemplate(Template):
    _template_dir = 'templates/default_project'
    summary = 'Pylons application template'
    egg_plugins = ['Pylons', 'WebHelpers']

class MinimalPylonsTemplate(Template):
    _template_dir = 'templates/minimal_project'
    summary = 'Pylons minimal application template'
    egg_plugins = ['Pylons', 'WebHelpers']

class PylonsInstaller(Installer):
    use_cheetah = False

__all__ = ['AttribSafeContextObj', 'ContextObj', 'Helpers',
           'class_name_from_module_name', 'log', '_', 'set_lang', 'get_lang']
__pudge_all__ = __all__ + ['MinimalPylonsTemplate', 'PylonsTemplate']
<commit_msg>[svn] small changes to AttribSafeContextObj.__repr__<commit_after>"""Paste Template and Pylons utility functions

PylonsTemplate is a Paste Template sub-class that configures the source
directory and default plug-ins for a new Pylons project. The minimal template
provides a more minimal template with less additional directories and layout.
"""
import warnings

from paste.script.appinstall import Installer
from paste.script.templates import Template

import pylons
import pylons.helpers
import pylons.i18n

def func_move(name, moved_to='pylons.i18n'):
    return ("The %s function has moved to %s, please update your import "
            "statements to reflect the move." % (name, moved_to))

def deprecated(func, message):
    def deprecated_method(*args, **kargs):
        warnings.warn(message, DeprecationWarning, 2)
        return func(*args, **kargs)
    try:
        deprecated_method.__name__ = func.__name__
    except TypeError: # Python < 2.4
        pass
    deprecated_method.__doc__ = message + "\n\n" + func.__doc__
    return deprecated_method

get_lang = deprecated(pylons.i18n.get_lang, func_move('get_lang'))
set_lang = deprecated(pylons.i18n.set_lang, func_move('set_lang'))
_ = deprecated(pylons.i18n._, func_move('_'))
log = deprecated(pylons.helpers.log, func_move('log',
                                               moved_to='pylons.helpers'))

def get_prefix(environ):
    if 'paste.config' in environ:
        prefix = environ['paste.config']['app_conf'].get('prefix', '')
    else:
        # Not ideal but if the error occurs before the paste.config is
        # available not a lot we can do
        prefix = ''
    if not prefix:
        if environ.get('SCRIPT_NAME', '') != '':
            prefix = environ['SCRIPT_NAME']
    return prefix

def class_name_from_module_name(module_name):
    """Takes a module name and returns the name of the class it defines.

    If the module name contains dashes, they are replaced with underscores.

    Example::

        >>> class_name_from_module_name('with-dashes')
        'WithDashes'
        >>> class_name_from_module_name('with_underscores')
        'WithUnderscores'
        >>> class_name_from_module_name('oneword')
        'Oneword'
    """
    words = module_name.replace('-', '_').split('_')
    return ''.join([w.title() for w in words])

def config_get(key, default=None):
    """Return a value from ``CONFIG``. Supports both ``paste.config.CONFIG``
    and the older ``paste.deploy.CONFIG``.

    This is for Pylons internal use only; to support both versions of the
    ``CONFIG`` objects, depending on which is used by the current Pylons
    web app."""
    try:
        # environ['paste.config'] is assured to be the correct CONFIG
        # during requests
        CONFIG = pylons.request.environ['paste.config']
        value = CONFIG['app_conf'].get(key, default)
    except TypeError:
        # TypeError: pylons.request isn't registered (this function call was
        # made outside of a web request). fall back to paste.config.CONFIG
        # directly, and finally paste.deploy.CONFIG
        try:
            from paste.config import CONFIG
            value = CONFIG['app_conf'].get(key, default)
        except AttributeError:
            from paste.deploy import CONFIG
            value = CONFIG['app_conf'].get(key, default)
    return value

class ContextObj(object):
    """ The 'c' object, with strict attribute access (raises an Exception when
    the attribute does not exist) """
    pass

class AttribSafeContextObj(object):
    """ The 'c' object, with lax attribute access (returns '' when the
    attribute does not exist) """
    def __getattr__(self, name):
        try:
            return object.__getattribute__(self, name)
        except AttributeError:
            return ''
    def __repr__(self):
        attrs = [(name, value)
                 for name, value in self.__dict__.items()
                 if not name.startswith('_')]
        attrs.sort()
        parts = []
        for name, value in attrs:
            value_repr = repr(value)
            if len(value_repr) > 70:
                value_repr = value_repr[:60] + '...' + value_repr[-5:]
            parts.append(' %s=%s' % (name, value_repr))
        return '<%s.%s at %s%s>' % (
            self.__class__.__module__,
            self.__class__.__name__,
            hex(id(self)),
            ','.join(parts))

class PylonsTemplate(Template):
    _template_dir = 'templates/default_project'
    summary = 'Pylons application template'
    egg_plugins = ['Pylons', 'WebHelpers']

class MinimalPylonsTemplate(Template):
    _template_dir = 'templates/minimal_project'
    summary = 'Pylons minimal application template'
    egg_plugins = ['Pylons', 'WebHelpers']

class PylonsInstaller(Installer):
    use_cheetah = False

__all__ = ['AttribSafeContextObj', 'ContextObj', 'Helpers',
           'class_name_from_module_name', 'log', '_', 'set_lang', 'get_lang']
__pudge_all__ = __all__ + ['MinimalPylonsTemplate', 'PylonsTemplate']
<|endoftext|>


<commit_before><commit_msg>: python unit , update encoding.<commit_after><|endoftext|>


<commit_before>"""
The Queue module.  This module handles the execution of time consuming tasks.
"""
from __future__ import absolute_import, with_statement

from subprocess import Popen, PIPE

#: The number of CPU's available on this system
ncpu = int(Popen(['sysctl', '-n', 'hw.ncpu'], stdout=PIPE).communicate()[0])

class WorkerQueue(object):
  """
     The WorkerQueue class.  This class manages a pool of worker threads for
     running jobs.
  """

  def __init__(self, name, load=1):
    """
       Initialise a worker thread pool

       @param name: The name of this thread (used in logging)
       @type name: C{str}
       @param load: The maximum load allowed
       @type load: C{int}
    """
    from logging import getLogger
    from threading import Condition, Lock
    # We have to use our own locks since we cannot access Queue's functions
    # without not holding the locks and doing this will cause a dead lock...
    self._lock = Condition(Lock())  #: The locker of this queue
    self._log = getLogger("pypkg.queue." + name)  #: Logger of this queue
    #self._name = name  #: The name of this queue
    self._load = load  #: The requested load
    self._curload = 0  #: The current load experianced

    self._wid = 0  #: The number of workers created (and next WID)
    self._jid = 0  #: The number of jobs created (and next JID)

    self._pool = {}  #: The pool of workers
    self._queue = []  #: Queue of jobs
    self._stalled = []  #: The stalled workers (with load and waker)

  def __len__(self):
    """
       The size of the worker pool

       @return: The worker pool size
       @rtype: C{int}
    """
    return len(self._pool) - len(self._stalled)

  def qsize(self):
    """
       The size of the queued items

       @return: The queue size
       @rtype: C{int}
    """
    return len(self._queue) + len(self._stalled)

  def jid(self):
    """
       Returns the current job ID.  Can only be called from a worker thread.

       @return: The current workers JID
       @rtype: C{int}
    """
    from threading import currentThread

    return self._pool[currentThread()][1]

  def job(self, jid):
    """
       Returns if the specified job has finished or not

       @param jid: The job ID (as returns by put)
       @type jid: C{int}
       @return: If the job has finished
       @rtype: C{bool}
    """
    with self._lock:
      for i in self._pool:
        if i[1] == jid:
          return False
      for i in self._queue:
        if i[1] == jid:
          return False

      return True

  def join(self):
    """
       Wait till all jobs have been consumed.
    """
    with self._lock:
      if self._pool:
        self._lock.wait()

  def load(self):
    """
       The current load allowed.  The actual number may vary but will hover
       around this figure.

       @return: Number of workers
       @rtype: C{int}
    """
    return self._workers

  def set_load(self, load):
    """
       Changes the current requested load.

       @param load: The load
       @type load: C{int}
    """
    with self._lock:
      self._load = load

      if not load:
        while self._stalled:
          worker = self._stalled.pop()
          self._curload += worker[1]
          worker[0].release()

  def put(self, func, load=1):
    """
       Places a job onto the queue, if insufficient workers are available one
       will be started.

       @param func: The job to execute
       @type func: C{callable}
       @param load: The load the job
       @type load: C{int}
    """
    assert callable(func)
    with self._lock:
      # If there is no load allowed then we are not open for jobs
      if not self._load:
        return -1

      self._jid += 1

      self._queue.append((func, self._jid, load))
      self._start()

      return self._jid

  def stats(self):
    """
       Returns a tuple about activity on the queue.
       (Workers running, Workers created, Jobs created)

       @return: The tuple of information
       @rtype: C{(int, int, int)}
    """
    return (len(self), self._wid, self_jid)

  def stalled(self):
    """
       Indicates if a worker has stalled.  This will result in a worker being
       created to replace this worker.

       NOTE: Can only be called from within a job

       @return: If stalling is possible
       @rtype: C{bool}
    """
    from threading import currentThread, Lock

    wid, jid, load = self._pool[currentThread()]
    lock = Lock()

    with lock:
      with self._lock:
        if not self._load:
          return False

        self._log.debug("Worker %d: Job %d stalled")
        self._stalled.append((lock, load))
        self._stalled += 1
        self._curload -= load
        self._start()

      # Wait for a worker to finish
      lock.acquire()
      self._log.debug("Worker %d: Job %d resuming")
      # `self._curload += load` called by waker
      # `self._stalled.remove((lock, load))` called by waker

    return bool(self._load)

  def terminate(self):
    """
       Shutdown this WorkerQueue.  Unlike set_load(0) all remaining queued
       items are also removed.
    """
    from Queue import Empty

    self.set_load(0)
    self._queue = []

  def _start(self):
    """
       Starts a worker if there is a need.

       NOTE: Must be called with lock held
    """
    assert not self._lock.acquire(False)

    while self._queue and self._curload < self._load:
      from threading import Thread

      job = self._find_job()

      self._wid += 1
      thread = Thread(target=lambda: self._worker(self._wid, job))
      self._pool[thread] = (self._wid,) + job[1:]
      self._curload += job[2]

      thread.start()

  def _find_job(self):
    """
       Finds an appropriate job to run.

       NOTE: Must be called with lock held (and len(self._queue) > 0)

       @return: The job to run
       @rtype: C{Callable, int, int}
    """
    assert not self._lock.acquire(False)
    assert self._curload < self._load and self._queue

    load = self._load - self._curload

    job = 0

    for i in xrange(len(self._queue)):
      if self._queue[i][2] <= load:
        return self._queue.pop(i)
      if self._queue[i][2] < self._queue[job][2]:
        job = i

    return self._queue.pop(job)

  def _find_worker(self):
    """
       Finds an appropriate stalled worker to run.

       NOTE: Must be called with lock held (and len(self._stalled) > 0)

       @return: The worker to wake
       @rtype: C{Lock, int}
    """
    assert not self._lock.acquire(False)
    assert self._curload < self._load and self._stalled

    load = self._load - self._curload

    worker = 0

    for i in xrange(len(self._stalled)):
      if self._stalled[i][1] <= load:
        return self._stalled.pop(i)
      if self._stalled[i][1] < self._stalled[worker][1]:
        worker = i

    return self._stalled.pop(worker)

  def _worker(self, wid, job):
    """
       The worker.  It waits for a job from the queue and then executes the
       given command (with given parameters).

       @param wid: The worker ID
       @type wid: C{int}
       @param job: The first job to run
       @type job: C{int, int, Callable}
    """
    from threading import currentThread
    from Queue import Empty

    thread = currentThread()

    self._log.debug("Worker %d: Created" % wid)

    while True:
      func, jid, load = job

      self._work(func, jid, wid)

      # Signal that a job has finished
      with self._lock:
        self._curload -= load

        while self._stalled and self._curload < self._load:
          worker = self._find_worker()
          self._curload += worker[1]
          worker[0].release()

        if self._curload >= self._load or not self._queue:
          break

        job = self._find_job()
        self._curload += job[2]
        self._start()

    self._pool.pop(thread)
    self._log.debug("Worker %d: Terminating" % wid)
    if not self._pool:
      with self._lock:
        self._lock.notifyAll()

  def _work(self, func, jid, wid):
    """
       Execute a job

       @param func: The job to run
       @type func: C{callable}
       @param jid: The job's ID
       @type jid: C{int}
       @param wid: The worker's ID
       @type wid: C{int}
    """
    self._log.debug("Worker %d: Starting job %d" % (wid, jid))

    try:
      func()
    except KeyboardInterrupt:
      from .exit import terminate
      terminate()
    except BaseException:
      self._log.exception("Worker %d: Job %d threw an exception" % (wid, jid))
    finally:
      self._log.debug("Worker %d: Finished job %d" % (wid, jid))

config_queue  = WorkerQueue("config", 1)  #: Queue for configuring port options
build_queue   = WorkerQueue("build", ncpu + 1)  #: Queue for building ports
fetch_queue   = WorkerQueue("fetch", 1)  #: Queue for fetching dist files
install_queue = WorkerQueue("install", 1)  #: Queue for installing ports
ports_queue   = WorkerQueue("ports", ncpu * 2)  #: Queue for fetching port info
queues        = [config_queue, build_queue, fetch_queue, install_queue,
                 ports_queue]  #: List of all the queues
<commit_msg>  - Give worker threads names<commit_after>"""
The Queue module.  This module handles the execution of time consuming tasks.
"""
from __future__ import absolute_import, with_statement

from subprocess import Popen, PIPE

#: The number of CPU's available on this system
ncpu = int(Popen(['sysctl', '-n', 'hw.ncpu'], stdout=PIPE).communicate()[0])

class WorkerQueue(object):
  """
     The WorkerQueue class.  This class manages a pool of worker threads for
     running jobs.
  """

  def __init__(self, name, load=1):
    """
       Initialise a worker thread pool

       @param name: The name of this thread (used in logging)
       @type name: C{str}
       @param load: The maximum load allowed
       @type load: C{int}
    """
    from logging import getLogger
    from threading import Condition, Lock
    # We have to use our own locks since we cannot access Queue's functions
    # without not holding the locks and doing this will cause a dead lock...
    self._lock = Condition(Lock())  #: The locker of this queue
    self._log = getLogger("pypkg.queue." + name)  #: Logger of this queue
    self._name = name  #: The name of this queue
    self._load = load  #: The requested load
    self._curload = 0  #: The current load experianced

    self._wid = 0  #: The number of workers created (and next WID)
    self._jid = 0  #: The number of jobs created (and next JID)

    self._pool = {}  #: The pool of workers
    self._queue = []  #: Queue of jobs
    self._stalled = []  #: The stalled workers (with load and waker)

  def __len__(self):
    """
       The size of the worker pool

       @return: The worker pool size
       @rtype: C{int}
    """
    return len(self._pool) - len(self._stalled)

  def qsize(self):
    """
       The size of the queued items

       @return: The queue size
       @rtype: C{int}
    """
    return len(self._queue) + len(self._stalled)

  def jid(self):
    """
       Returns the current job ID.  Can only be called from a worker thread.

       @return: The current workers JID
       @rtype: C{int}
    """
    from threading import currentThread

    return self._pool[currentThread()][1]

  def job(self, jid):
    """
       Returns if the specified job has finished or not

       @param jid: The job ID (as returns by put)
       @type jid: C{int}
       @return: If the job has finished
       @rtype: C{bool}
    """
    with self._lock:
      for i in self._pool:
        if i[1] == jid:
          return False
      for i in self._queue:
        if i[1] == jid:
          return False

      return True

  def join(self):
    """
       Wait till all jobs have been consumed.
    """
    with self._lock:
      if self._pool:
        self._lock.wait()

  def load(self):
    """
       The current load allowed.  The actual number may vary but will hover
       around this figure.

       @return: Number of workers
       @rtype: C{int}
    """
    return self._workers

  def set_load(self, load):
    """
       Changes the current requested load.

       @param load: The load
       @type load: C{int}
    """
    with self._lock:
      self._load = load

      if not load:
        while self._stalled:
          worker = self._stalled.pop()
          self._curload += worker[1]
          worker[0].release()

  def put(self, func, load=1):
    """
       Places a job onto the queue, if insufficient workers are available one
       will be started.

       @param func: The job to execute
       @type func: C{callable}
       @param load: The load the job
       @type load: C{int}
    """
    assert callable(func)
    with self._lock:
      # If there is no load allowed then we are not open for jobs
      if not self._load:
        return -1

      self._jid += 1

      self._queue.append((func, self._jid, load))
      self._start()

      return self._jid

  def stats(self):
    """
       Returns a tuple about activity on the queue.
       (Workers running, Workers created, Jobs created)

       @return: The tuple of information
       @rtype: C{(int, int, int)}
    """
    return (len(self), self._wid, self_jid)

  def stalled(self):
    """
       Indicates if a worker has stalled.  This will result in a worker being
       created to replace this worker.

       NOTE: Can only be called from within a job

       @return: If stalling is possible
       @rtype: C{bool}
    """
    from threading import currentThread, Lock

    wid, jid, load = self._pool[currentThread()]
    lock = Lock()

    with lock:
      with self._lock:
        if not self._load:
          return False

        self._log.debug("Worker %d: Job %d stalled")
        self._stalled.append((lock, load))
        self._stalled += 1
        self._curload -= load
        self._start()

      # Wait for a worker to finish
      lock.acquire()
      self._log.debug("Worker %d: Job %d resuming")
      # `self._curload += load` called by waker
      # `self._stalled.remove((lock, load))` called by waker

    return bool(self._load)

  def terminate(self):
    """
       Shutdown this WorkerQueue.  Unlike set_load(0) all remaining queued
       items are also removed.
    """
    from Queue import Empty

    self.set_load(0)
    self._queue = []

  def _start(self):
    """
       Starts a worker if there is a need.

       NOTE: Must be called with lock held
    """
    assert not self._lock.acquire(False)

    while self._queue and self._curload < self._load:
      from threading import Thread

      job = self._find_job()

      self._wid += 1
      thread = Thread(target=lambda: self._worker(self._wid, job))
      self._pool[thread] = (self._wid,) + job[1:]
      self._curload += job[2]

      thread.start()

  def _find_job(self):
    """
       Finds an appropriate job to run.

       NOTE: Must be called with lock held (and len(self._queue) > 0)

       @return: The job to run
       @rtype: C{Callable, int, int}
    """
    assert not self._lock.acquire(False)
    assert self._curload < self._load and self._queue

    load = self._load - self._curload

    job = 0

    for i in xrange(len(self._queue)):
      if self._queue[i][2] <= load:
        return self._queue.pop(i)
      if self._queue[i][2] < self._queue[job][2]:
        job = i

    return self._queue.pop(job)

  def _find_worker(self):
    """
       Finds an appropriate stalled worker to run.

       NOTE: Must be called with lock held (and len(self._stalled) > 0)

       @return: The worker to wake
       @rtype: C{Lock, int}
    """
    assert not self._lock.acquire(False)
    assert self._curload < self._load and self._stalled

    load = self._load - self._curload

    worker = 0

    for i in xrange(len(self._stalled)):
      if self._stalled[i][1] <= load:
        return self._stalled.pop(i)
      if self._stalled[i][1] < self._stalled[worker][1]:
        worker = i

    return self._stalled.pop(worker)

  def _worker(self, wid, job):
    """
       The worker.  It waits for a job from the queue and then executes the
       given command (with given parameters).

       @param wid: The worker ID
       @type wid: C{int}
       @param job: The first job to run
       @type job: C{int, int, Callable}
    """
    from threading import currentThread
    from Queue import Empty

    thread = currentThread()
    thread.name = self._name[0].upper() + self._name[1:] + "Worker-%i" % wid

    self._log.debug("Worker %d: Created" % wid)

    while True:
      func, jid, load = job

      self._work(func, jid, wid)

      # Signal that a job has finished
      with self._lock:
        self._curload -= load

        while self._stalled and self._curload < self._load:
          worker = self._find_worker()
          self._curload += worker[1]
          worker[0].release()

        if self._curload >= self._load or not self._queue:
          break

        job = self._find_job()
        self._curload += job[2]
        self._start()

    self._pool.pop(thread)
    self._log.debug("Worker %d: Terminating" % wid)
    if not self._pool:
      with self._lock:
        self._lock.notifyAll()

  def _work(self, func, jid, wid):
    """
       Execute a job

       @param func: The job to run
       @type func: C{callable}
       @param jid: The job's ID
       @type jid: C{int}
       @param wid: The worker's ID
       @type wid: C{int}
    """
    self._log.debug("Worker %d: Starting job %d" % (wid, jid))

    try:
      func()
    except KeyboardInterrupt:
      from .exit import terminate
      terminate()
    except BaseException:
      self._log.exception("Worker %d: Job %d threw an exception" % (wid, jid))
    finally:
      self._log.debug("Worker %d: Finished job %d" % (wid, jid))

config_queue  = WorkerQueue("config", 1)  #: Queue for configuring port options
build_queue   = WorkerQueue("build", ncpu + 1)  #: Queue for building ports
fetch_queue   = WorkerQueue("fetch", 1)  #: Queue for fetching dist files
install_queue = WorkerQueue("install", 1)  #: Queue for installing ports
ports_queue   = WorkerQueue("ports", ncpu * 2)  #: Queue for fetching port info
queues        = [config_queue, build_queue, fetch_queue, install_queue,
                 ports_queue]  #: List of all the queues
<|endoftext|>


<commit_before>import BaseHTTPServer

router = {}

class Server(BaseHTTPServer.HTTPServer):
    pass

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        pass

    def do_POST(self):
        pass

    def do_PUT(self):
        pass

    def do_DELETE(self):
        pass

class Application():
    def __init__(self):
        pass

    def route(fn):
        def wrapper(*args, **kwargs):
            pass
        return wrapper

    def listen(port=1337, hostname='', backlog=511, callback=None):
        server = Server(hostname, port, self.app)
        server.serve_forever()

<commit_msg>basic middleware mounting<commit_after>import BaseHTTPServer
from .request import Request
from .response import Response
from .router import Router

class PypressServer(BaseHTTPServer.HTTPServer):
    pass

class PypressRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def handle_request(self):
        pass

    do_GET = handle_request
    do_POST = handle_request
    do_PUT = handle_request
    do_PATCH = handle_request
    do_DELETE = handle_request

class Application():
    Router = Router

    def __init__(self):
        self.routes = {}

    # helper method to mount middleware for the given route and method.
    # if no method is provided, mount the middleware for all methods.
    def _mount_middleware(self, path, middleware, method=None):
        middleware = [m for m in middleware]
        if not self.routes[path]:
            self.routes[path] = {} if method else []
        if method:
            # mount middleware for method
            if not self.routes[path][method]:
                self.routes[path][method] = []
            self.routes[path][method] += middleware
        else:
            self.routes.path += middleware

    # mount the middleware for all requests to the path.
    def use(self, path, *middleware):
        if middleware:
            self._mount_middleware(path, middleware)
        else:
            def add_route(f):
                self.routes[path] = f
            return add_route

    # mount the middleware for all GET requests to the path.
    def get(self, path, *middleware):
        if middleware:
            self._mount_middleware(path, middleware, 'GET')
        else:
            def add_route(f):
                self.routes[path] = f
            return add_route

    # mount the middleware for all POST requests to the path.
    def post(self, path, *middleware):
        if middleware:
            self.routes[path] = middleware
        else:
            def add_route(f):
                self.routes[path] = f
            return add_route

    # mount the middleware for all PUT requests to the path.
    def put(self, path, *middleware):
        if middleware:
            self.routes[path] = middleware
        else:
            def add_route(f):
                self.routes[path] = f
            return add_route

    # mount the middleware for all GET requests to the path.
    def patch(self, path, *middleware):
        if middleware:
            self.routes[path] = middleware
        else:
            def add_route(f):
                self.routes[path] = f
            return add_route

    # mount the middleware for all DELETE requests to the path.
    def delete(self, path, *middleware):
        if middleware:
            self.routes[path] = middleware
        else:
            def add_route(f):
                self.routes[path] = f
            return add_route

    def listen(port=1337, hostname='0.0.0.0', backlog=511, callback=None):
        server = PypressServer((hostname, port), PypressRequestHandler)
        server.serve_forever()
<|endoftext|>