예제 #1
0
파일: posix_process.py 프로젝트: delicb/tea
def get_processes(sort_by_name=True, cmdline=False):
    if platform.is_a(platform.DARWIN):
        process = PosixProcess('ps', ['-eo', 'pid,comm,args' if cmdline
                                             else 'pid,comm'])
    else:
        process = PosixProcess('ps', ['h', '-eo', 'pid,comm,args' if cmdline
                                                  else 'pid,comm'])
    process.start()
    process.wait()
    processes = []
    if process.exit_code == 0:
        for line in process.read().splitlines():
            if cmdline:
                parts = line.strip().split(' ', 3)
                try:
                    processes.append((int(parts[0]), parts[1],
                                      ' '.join(parts[2:]).strip()))
                except ValueError:
                    logger.error('Failed to parse PID: %s' % parts[0])
            else:
                pid, name = line.strip().split(' ', 1)
                try:
                    processes.append((int(pid), name))
                except ValueError:
                    logger.error('Failed to parse PID: %s' % pid)
    if sort_by_name:
        return sorted(processes, lambda t1, t2: (cmp(t1[1], t2[1]) or
                                                 cmp(int(t1[0]), int(t2[0]))))
    else:
        return sorted(processes, lambda t1, t2: (cmp(int(t1[0]), int(t2[0])) or
                                                 cmp(t1[1], t2[1])))
예제 #2
0
    def test_eread(self):
        p = Process(
            sys.executable,
            [
                "-c",
                """import sys, time
sys.stderr.write('foo')
sys.stderr.flush()
time.sleep(2)
sys.stderr.write('bar')
""",
            ],
        )
        p.start()
        if platform.is_a(platform.DOTNET):
            # TODO: .NET does not flush the outputs
            p.wait()
            self.assertEqual(p.read(), b"")
            self.assertEqual(p.eread(), b"foobar")
        else:
            time.sleep(1)
            self.assertEqual(p.read(), b"")
            self.assertEqual(p.eread(), b"foo")
            p.wait()
            self.assertEqual(p.read(), b"")
            self.assertEqual(p.eread(), b"bar")
예제 #3
0
 def __init__(self, *args, **kwargs):
     super(Configuration, self).__init__(*args, **kwargs)
     self.__repositories = None
     # Executables
     # TODO: Not actually cross platform
     if platform.is_a(platform.WINDOWS):
         self.executables = LambdaDict({
             '7z':
             lambda: utils.find_exe('pf', ['7-Zip', '7z.exe'], '7z.exe'),
             'devenv':
             lambda: utils.find_exe('pf', [
                 'Microsoft Visual Studio 1?.0', 'Common7', 'IDE',
                 'devenv.com'
             ], 'devenv.com'),  # MUST BE .COM!!! NOT .EXE!!!
             'msbuild':
             lambda: utils.find_exe('win', [
                 'Microsoft.NET', 'Framework', 'v4.0.30319', 'msbuild.exe'
             ], 'msbuild.exe'),
             'msbuild_2008':
             lambda: utils.find_exe('win', [
                 'Microsoft.NET', 'Framework', 'v3.5', 'msbuild.exe'
             ], 'msbuild.exe'),
             'nunit':
             lambda: utils.find_exe('pf', [
                 'NUnit 2.*.*', 'bin', 'net-2.0', 'nunit-console.exe'
             ], 'nunit-console.exe'),
             'ipy':
             lambda: utils.find_exe('pf', ['IronPython 2.7', 'ipy64.exe'],
                                    'ipy64.exe'),
             'python':
             lambda: utils.find_exe(
                 None, ['C:\\', 'Python2*', 'python.exe'], 'python.exe'),
             'tortoisehg':
             lambda: utils.find_exe('pf', ['TortoiseHg', 'thg.exe'],
                                    'thg.exe'),
         })
     elif platform.is_a(platform.POSIX):
         self.executables = {
             '7z': '7z',
             'msbuild': 'xbuild',
             'python': 'python',
         }
예제 #4
0
파일: open.py 프로젝트: delicb/samovar
 def open(self, what, path):
     path = os.path.abspath(path)
     if what == 'cmd':
         if platform.is_a(platform.WINDOWS):
             os.system('start cmd /k cd /d "%s"' % path)
         elif platform.is_a(platform.DARWIN):
             result = os.system('open -a iTerm "%s"' % path)
             if result != 0:
                 os.system('open -a Terminal "%s"' % path)
     elif what == 'fm':
         import webbrowser
         if platform.is_a(platform.DARWIN):
             webbrowser.open('file://' % path)
         else:
             webbrowser.open(path)
     elif what == 'thg':
         executable = self.config.executables[what]
         status, output, _ = execute(executable, '--repository', path)
         if status != 0:
             cprint('Unable to opet tortoiseHg.\n', Color.red)
             cprint('%s' % output)
예제 #5
0
파일: compress.py 프로젝트: SenadI/tea
def _get_sz():
    global _SZ_EXECUTABLE
    if _SZ_EXECUTABLE is None:
        _SZ_EXECUTABLE = '7z'
        if platform.is_a(platform.WINDOWS):
            for pf in ('ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432'):
                executable = os.path.join(os.environ.get(pf, ''), '7-Zip',
                                          '7z.exe')
                if os.path.exists(executable):
                    _SZ_EXECUTABLE = executable
                    break
    return _SZ_EXECUTABLE
예제 #6
0
파일: compress.py 프로젝트: delicb/tea
def _get_sz():
    global _SZ_EXECUTABLE
    if _SZ_EXECUTABLE is None:
        _SZ_EXECUTABLE = '7z'
        if platform.is_a(platform.WINDOWS):
            for pf in ('ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432'):
                executable = os.path.join(os.environ.get(pf, ''), '7-Zip',
                                          '7z.exe')
                if os.path.exists(executable):
                    _SZ_EXECUTABLE = executable
                    break
    return _SZ_EXECUTABLE
예제 #7
0
파일: open.py 프로젝트: delicb/samovar
 def open(self, what, path):
     path = os.path.abspath(path)
     if what == 'cmd':
         if platform.is_a(platform.WINDOWS):
             os.system('start cmd /k cd /d "%s"' % path)
         elif platform.is_a(platform.DARWIN):
             result = os.system('open -a iTerm "%s"' % path)
             if result != 0:
                 os.system('open -a Terminal "%s"' % path)
     elif what == 'fm':
         import webbrowser
         if platform.is_a(platform.DARWIN):
             webbrowser.open('file://' % path)
         else:
             webbrowser.open(path)
     elif what == 'thg':
         executable = self.config.executables[what]
         status, output, _ = execute(executable, '--repository', path)
         if status != 0:
             cprint('Unable to opet tortoiseHg.\n', Color.red)
             cprint('%s' % output)
예제 #8
0
파일: config.py 프로젝트: delicb/samovar
 def __init__(self, *args, **kwargs):
     super(Configuration, self).__init__(*args, **kwargs)
     self.__repositories    = None
     # Executables
     # TODO: Not actually cross platform
     if platform.is_a(platform.WINDOWS):
         self.executables = LambdaDict({
             '7z'           : lambda: utils.find_exe('pf',  ['7-Zip', '7z.exe'], '7z.exe'),
             'devenv'       : lambda: utils.find_exe('pf',  ['Microsoft Visual Studio 1?.0', 'Common7', 'IDE', 'devenv.com'], 'devenv.com'),  # MUST BE .COM!!! NOT .EXE!!!
             'msbuild'      : lambda: utils.find_exe('win', ['Microsoft.NET', 'Framework', 'v4.0.30319', 'msbuild.exe'], 'msbuild.exe'),
             'msbuild_2008' : lambda: utils.find_exe('win', ['Microsoft.NET', 'Framework', 'v3.5', 'msbuild.exe'], 'msbuild.exe'),
             'nunit'        : lambda: utils.find_exe('pf',  ['NUnit 2.*.*', 'bin', 'net-2.0', 'nunit-console.exe'], 'nunit-console.exe'),
             'ipy'          : lambda: utils.find_exe('pf',  ['IronPython 2.7', 'ipy64.exe'], 'ipy64.exe'),
             'python'       : lambda: utils.find_exe(None,  ['C:\\', 'Python2*', 'python.exe'], 'python.exe'),
             'tortoisehg'   : lambda: utils.find_exe('pf',  ['TortoiseHg', 'thg.exe'], 'thg.exe'),
         })
     elif platform.is_a(platform.POSIX):
         self.executables = {
             '7z'           : '7z',
             'msbuild'      : 'xbuild',
             'python'       : 'python',
         }
예제 #9
0
파일: compress.py 프로젝트: alefnula/tea
def _get_sz():
    global _SZ_EXECUTABLE
    if _SZ_EXECUTABLE is None:
        _SZ_EXECUTABLE = "7z"
        if platform.is_a(platform.WINDOWS):
            for pf in ("ProgramFiles", "ProgramFiles(x86)", "ProgramW6432"):
                executable = os.path.join(
                    os.environ.get(pf, ""), "7-Zip", "7z.exe"
                )
                if os.path.exists(executable):
                    _SZ_EXECUTABLE = executable
                    break
    return _SZ_EXECUTABLE
예제 #10
0
파일: test_process.py 프로젝트: SenadI/tea
def test_eread():
    p = Process(sys.executable, ['-c', WRITER.format(out='stderr')])
    p.start()
    if platform.is_a(platform.DOTNET):
        # TODO: .NET does not flush the outputs
        p.wait()
        assert p.read() == b''
        assert p.eread() == b'foobar'
    else:
        time.sleep(1)
        assert p.read() == b''
        assert p.eread() == b'foo'
        p.wait()
        assert p.read() == b''
        assert p.eread() == b'bar'
예제 #11
0
def test_eread():
    p = Process(sys.executable, ["-c", WRITER.format(out="stderr")])
    p.start()
    if platform.is_a(platform.DOTNET):
        # TODO: .NET does not flush the outputs
        p.wait()
        assert p.read() == b""
        assert p.eread() == b"foobar"
    else:
        time.sleep(1)
        assert p.read() == b""
        assert p.eread() == b"foo"
        p.wait()
        assert p.read() == b""
        assert p.eread() == b"bar"
예제 #12
0
파일: daemon.py 프로젝트: alefnula/tea
from __future__ import print_function

__author__ = "Viktor Kerkez <*****@*****.**>"
__date__ = "18 September 2012"
__copyright__ = "Copyright (c) 2013 Viktor Kerkez"

import io
import os
import sys
import time
import atexit
from signal import SIGTERM

from tea.system import platform

if platform.is_a(platform.POSIX):

    class Daemon(object):
        """Generic daemon class.

        Usage: subclass the Daemon class and override the run() method
        """

        def __init__(
            self,
            pidfile,
            stdin="/dev/null",
            stdout="/dev/null",
            stderr="/dev/null",
        ):
            self.stdin = stdin
예제 #13
0
파일: wrapper.py 프로젝트: alefnula/tea
__all__ = [
    "execute",
    "execute_and_report",
    "Process",
    "find",
    "get_processes",
    "kill",
]

import os
import logging
from functools import cmp_to_key
from tea.utils import cmp
from tea.system import platform

if platform.is_a(platform.DOTNET):
    from tea.process.dotnet_process import DotnetProcess as Process
    from tea.process.dotnet_process import _list_processes, kill
elif platform.is_a(platform.WINDOWS):
    from tea.process.win_process import WinProcess as Process
    from tea.process.win_process import _list_processes, kill
elif platform.is_a(platform.POSIX):
    from tea.process.posix_process import PosixProcess as Process
    from tea.process.posix_process import _list_processes, kill
else:
    raise platform.not_supported("tea.process")


logger = logging.getLogger(__name__)

예제 #14
0
 def test_yaml_yaml(self):
     if platform.is_a(platform.DOTNET):
         self.skipTest('YAML is not supported on .NET')
     c = MultiConfig(data=self.yaml_first, fmt=Config.YAML)
     c.attach(data=self.yaml_second, fmt=Config.YAML)
     self.check_structure(c)
예제 #15
0
    gray = 'gray'
    white = 'white'
    normal = 'normal'

    @classmethod
    def colors(cls):
        return (cls.black, cls.blue, cls.green, cls.cyan, cls.red, cls.purple,
                cls.yellow, cls.gray, cls.white, cls.normal)

    @classmethod
    def color_re(cls):
        return re.compile(r'\[(?P<dark>dark )?(?P<color>%s)\]' %
                          '|'.join(cls.colors()), re.MULTILINE)


if platform.is_a(platform.WINDOWS | platform.DOTNET):

    # COLORS[fg or bg][is dark][color]
    COLORS = {
        'fg': {
            True: {Color.black: 0x00, Color.blue: 0x01, Color.green: 0x02,
                   Color.cyan: 0x03, Color.red: 0x04, Color.purple: 0x05,
                   Color.yellow: 0x06, Color.white: 0x07, Color.gray: 0x08,
                   Color.normal: 0x07},
            False: {Color.black: 0x00, Color.blue: 0x09, Color.green: 0x0A,
                    Color.cyan: 0x0B, Color.red: 0x0C, Color.purple: 0x0D,
                    Color.yellow: 0x0E, Color.white: 0x0F,
                    Color.gray: 0x07, Color.normal: 0x07}
        },
        'bg': {
            True: {Color.black: 0x00, Color.blue: 0x10, Color.green: 0x20,
예제 #16
0
 def test_yaml_yaml(self):
     if platform.is_a(platform.DOTNET):
         self.skipTest('YAML is not supported on .NET')
     c = MultiConfig(data=self.yaml_first, fmt=Config.YAML)
     c.attach(data=self.yaml_second, fmt=Config.YAML)
     self.check_structure(c)
예제 #17
0
파일: crypto.py 프로젝트: delicb/tea
        # TODO: There is a bug with saving and getting key from vault
        #       probably something with encoding. Sometimes _vault_retrieve
        #       returns numbers higher then 255 (even if they were not stored)
        @keygetter
        def get_key():
            key = _vault_retrieve('tea', 'tea-crypt')
            if key:
                return [ord(k) % 256 for k in key]
            else:
                key = _generate_key()
                _vault_store('tea', 'tea-crypt', ''.join(map(chr, key)))
                return key
    except ImportError:
        pass

elif platform.is_a(platform.DOTNET):
    # ironpython - .net implementation of AES can be used
    # ironpython can be used on mono so check what options are for key storage
    import clr
    clr.AddReference('System.Security')
    from System import Array, Byte
    from System.Text import UTF8Encoding
    from System.IO import MemoryStream
    from System.Security.Cryptography import (RijndaelManaged, CryptoStream,
                                              CryptoStreamMode, ProtectedData,
                                              DataProtectionScope)

    @encrypter('dotnet')
    def _encrypt(text, key):
        """Performs crypting of provided text using AES algorithm.
예제 #18
0
파일: test_config.py 프로젝트: alefnula/tea
def test_data_yaml():
    if platform.is_a(platform.DOTNET):
        pytest.skip("YAML is not supported on .NET")
    check_values(Config(data=YAML_DATA, fmt=Config.YAML))
예제 #19
0
파일: daemon.py 프로젝트: SenadI/tea
from __future__ import print_function

__author__ = 'Viktor Kerkez <*****@*****.**>'
__date__ = '18 September 2012'
__copyright__ = 'Copyright (c) 2013 Viktor Kerkez'

import io
import os
import sys
import time
import atexit
from signal import SIGTERM

from tea.system import platform

if platform.is_a(platform.POSIX):
    class Daemon(object):
        """A generic daemon class.

        Usage: subclass the Daemon class and override the run() method
        """
        def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null',
                     stderr='/dev/null'):
            self.stdin = stdin
            self.stdout = stdout
            self.stderr = stderr
            self.pidfile = pidfile

        def daemonize(self):
            """Do the UNIX double-fork magic
예제 #20
0
파일: sv.py 프로젝트: rubyengineer/samovar
__author__ = "Viktor Kerkez <*****@*****.**>"
__date__ = "02 January 2013"
__copyright__ = "Copyright (c) 2013 Viktor Kerkez"

import os
import sys
import time

PREFIX = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
sys.path.extend([os.path.join(PREFIX, "tea", "src"), os.path.join(PREFIX, "samovar", "src")])

from tea import shutil
from tea.utils.six.moves import input
from tea.system import platform

if platform.is_a(platform.WINDOWS):
    get_time = time.clock
else:
    get_time = time.time

# FIXME: Read from existing commands and their options (aliases, repositories...)
commands = {
    "branch": [],
    "branches": [],
    "churn": ["--sort", "--diffstat", "--changesets"],
    "clone": ["--delete"],
    "commit": ["--addremove", "--message", "--amend", "--user"],
    "diff": [
        "--rev",
        "--change",
        "--show-functions",
예제 #21
0
def test_data_yaml():
    if platform.is_a(platform.DOTNET):
        pytest.skip('YAML is not supported on .NET')
    check_values(Config(data=YAML_DATA, fmt=Config.YAML))
예제 #22
0
 def test_data_yaml(self):
     if platform.is_a(platform.DOTNET):
         self.skipTest("YAML is not supported on .NET")
     self.c = Config(data=YAML_DATA, fmt=Config.YAML)
     self.safe_check_values()
예제 #23
0
        # TODO: There is a bug with saving and getting key from vault
        #       probably something with encoding. Sometimes _vault_retrieve
        #       returns numbers higher then 255 (even if they were not stored)
        @keygetter
        def get_key():
            key = _vault_retrieve('tea', 'tea-crypt')
            if key:
                return [ord(k) % 256 for k in key]
            else:
                key = _generate_key()
                _vault_store('tea', 'tea-crypt', ''.join(map(chr, key)))
                return key
    except ImportError:
        pass

elif platform.is_a(platform.DOTNET):
    # ironpython - .net implementation of AES can be used
    # ironpython can be used on mono so check what options are for key storage
    import clr
    clr.AddReference('System.Security')
    from System import Array, Byte
    from System.Text import UTF8Encoding
    from System.IO import MemoryStream
    from System.Security.Cryptography import (RijndaelManaged, CryptoStream,
                                              CryptoStreamMode, ProtectedData,
                                              DataProtectionScope)

    @encrypter('dotnet')
    def _dotnet_encrypt(text, key):
        """Performs crypting of provided text using AES algorithm.
예제 #24
0
__copyright__ = 'Copyright (c) 2013 Viktor Kerkez'

import os
import sys
import time

PREFIX = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.extend([
    os.path.join(PREFIX, 'tea',     'src'),
    os.path.join(PREFIX, 'samovar', 'src'),
])

from tea import shutil
from tea.utils.six.moves import input
from tea.system import platform
if platform.is_a(platform.WINDOWS):
    get_time = time.clock
else:
    get_time = time.time

# FIXME: Read from existing commands and their options (aliases, repositories...)
commands = {
    'branch'     : [],
    'branches'   : [],
    'churn'      : ['--sort', '--diffstat', '--changesets'],
    'clone'      : ['--delete'],
    'commit'     : ['--addremove', '--message', '--amend', '--user'],
    'diff'       : ['--rev', '--change', '--show-functions', '--reverse', 
                    '--ignore-all-space', '--ignore-blank-lines', '--unified', 
                    '--stat'],
    'fetch'      : [],