# Path: autopush/gcdump.py
# class Stat(object):
#     summary = {}
#     typeids = {0: '<GCROOT>'}
# 
#     def summarize(self, filename, stream=None):
#         a = self.load_dump_file(filename)
#         self.summary = {}     # {typenum: [count, totalsize]}
#         for obj in self.walk(a, stream=stream):
#             self.add_object_summary(obj[2], obj[3])
# 
#     def load_typeids(self, filename_or_iter):
#         self.typeids = Stat.typeids.copy()
#         if isinstance(filename_or_iter, str):
#             iter = open(filename_or_iter)
#         else:
#             iter = filename_or_iter
#         for num, line in enumerate(iter):
#             if num == 0:
#                 continue
#             if not line:
#                 continue
#             words = line.split()
#             if words[0].startswith('member'):
#                 del words[0]
#             if words[0] == 'GcStruct':
#                 del words[0]
#             self.typeids[num] = ' '.join(words)
# 
#     def get_type_name(self, num):
#         return self.typeids.get(num, '<typenum %d>' % num)
# 
#     def print_summary(self, stream):
#         items = self.summary.items()
#         items.sort(key=lambda (typenum, stat): stat[1])    # sort by totalsize
#         totalsize = 0
#         for typenum, stat in items:
#             totalsize += stat[1]
#             stream.write('%8d %8.2fM  %s\n' %
#                          (stat[0],
#                           stat[1] / (1024.0*1024.0),
#                           self.get_type_name(typenum)))
#         stream.write('total %.1fM\n' % (totalsize / (1024.0*1024.0)))
# 
#     def load_dump_file(self, filename):
#         f = open(filename, 'rb')
#         f.seek(0, 2)
#         end = f.tell()
#         f.seek(0)
#         a = array.array('l')
#         a.fromfile(f, end / struct.calcsize('l'))
#         f.close()
#         return a
# 
#     def add_object_summary(self, typenum, sizeobj):
#         try:
#             stat = self.summary[typenum]
#         except KeyError:
#             stat = self.summary[typenum] = [0, 0]
#         stat[0] += 1
#         stat[1] += sizeobj
# 
#     def walk(self, a, start=0, stop=None, stream=None):
#         assert a[-1] == -1, "invalid or truncated dump file (or 32/64-bit mix)"
#         assert a[-2] != -1, "invalid or truncated dump file (or 32/64-bit mix)"
#         if stream:
#             stream.write('walking...')
#         i = start
#         if stop is None:
#             stop = len(a)
#         while i < stop:
#             j = i + 3
#             while a[j] != -1:
#                 j += 1
#             yield (i, a[i], a[i+1], a[i+2], a[i+3:j])
#             i = j + 1
#         if stream:
#             stream.write('done\n')


import gc
import objgraph
import os
import resource
import subprocess
import tempfile
import zlib
        import pypyjit
from StringIO import StringIO
from typing import Optional  # noqa
from autopush.gcdump import Stat
from cffi import FFI
    """Write pmap (w/ the most extended stats supported) to stream"""
    pid = str(os.getpid())
    # -XX/-X are recent linux only
    ex_args = ['XX', 'X', 'x']
    while True:
        cmd = ['pmap', '-' + ex_args.pop(0), pid]
        try:
            pmap = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError:  # pragma: nocover
            if not ex_args:
                raise
        else:
            stream.writelines([' '.join(cmd[:2]), '\n', pmap, '\n\n'])
            break


def dump_rpy_heap(stream):  # pragma: nocover
    """Write PyPy's gcdump to the specified stream"""
    if not hasattr(gc, '_dump_rpy_heap'):
        # not PyPy
        return

    with tempfile.NamedTemporaryFile('wb') as fp:
        gc._dump_rpy_heap(fp.fileno())
        try:
            fpsize = os.stat(fp.name).st_size
        except OSError:
            pass
        else:
            stream.write("{} size: {}\n".format(fp.name, fpsize))

# Path: autopush/gcdump.py
# class Stat(object):
#     summary = {}
#     typeids = {0: '<GCROOT>'}
# 
#     def summarize(self, filename, stream=None):
#         a = self.load_dump_file(filename)
#         self.summary = {}     # {typenum: [count, totalsize]}
#         for obj in self.walk(a, stream=stream):
#             self.add_object_summary(obj[2], obj[3])
# 
#     def load_typeids(self, filename_or_iter):
#         self.typeids = Stat.typeids.copy()
#         if isinstance(filename_or_iter, str):
#             iter = open(filename_or_iter)
#         else:
#             iter = filename_or_iter
#         for num, line in enumerate(iter):
#             if num == 0:
#                 continue
#             if not line:
#                 continue
#             words = line.split()
#             if words[0].startswith('member'):
#                 del words[0]
#             if words[0] == 'GcStruct':
#                 del words[0]
#             self.typeids[num] = ' '.join(words)
# 
#     def get_type_name(self, num):
#         return self.typeids.get(num, '<typenum %d>' % num)
# 
#     def print_summary(self, stream):
#         items = self.summary.items()
#         items.sort(key=lambda (typenum, stat): stat[1])    # sort by totalsize
#         totalsize = 0
#         for typenum, stat in items:
#             totalsize += stat[1]
#             stream.write('%8d %8.2fM  %s\n' %
#                          (stat[0],
#                           stat[1] / (1024.0*1024.0),
#                           self.get_type_name(typenum)))
#         stream.write('total %.1fM\n' % (totalsize / (1024.0*1024.0)))
# 
#     def load_dump_file(self, filename):
#         f = open(filename, 'rb')
#         f.seek(0, 2)
#         end = f.tell()
#         f.seek(0)
#         a = array.array('l')
#         a.fromfile(f, end / struct.calcsize('l'))
#         f.close()
#         return a
# 
#     def add_object_summary(self, typenum, sizeobj):
#         try:
#             stat = self.summary[typenum]
#         except KeyError:
#             stat = self.summary[typenum] = [0, 0]
#         stat[0] += 1
#         stat[1] += sizeobj
# 
#     def walk(self, a, start=0, stop=None, stream=None):
#         assert a[-1] == -1, "invalid or truncated dump file (or 32/64-bit mix)"
#         assert a[-2] != -1, "invalid or truncated dump file (or 32/64-bit mix)"
#         if stream:
#             stream.write('walking...')
#         i = start
#         if stop is None:
#             stop = len(a)
#         while i < stop:
#             j = i + 3
#             while a[j] != -1:
#                 j += 1
#             yield (i, a[i], a[i+1], a[i+2], a[i+3:j])
#             i = j + 1
#         if stream:
#             stream.write('done\n')


# Path: autopush/memusage.py
import gc
import objgraph
import os
import resource
import subprocess
import tempfile
import zlib
        import pypyjit
from StringIO import StringIO
from typing import Optional  # noqa
from autopush.gcdump import Stat
from cffi import FFI

    """Write pmap (w/ the most extended stats supported) to stream"""
    pid = str(os.getpid())
    # -XX/-X are recent linux only
    ex_args = ['XX', 'X', 'x']
    while True:
        cmd = ['pmap', '-' + ex_args.pop(0), pid]
        try:
            pmap = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError:  # pragma: nocover
            if not ex_args:
                raise
        else:
            stream.writelines([' '.join(cmd[:2]), '\n', pmap, '\n\n'])
            break


def dump_rpy_heap(stream):  # pragma: nocover
    """Write PyPy's gcdump to the specified stream"""
    if not hasattr(gc, '_dump_rpy_heap'):
        # not PyPy
        return

    with tempfile.NamedTemporaryFile('wb') as fp:
        gc._dump_rpy_heap(fp.fileno())
        try:
            fpsize = os.stat(fp.name).st_size
        except OSError:
            pass
        else:
            stream.write("{} size: {}\n".format(fp.name, fpsize))

        stat = Stat()