prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): <|fim_middle|> @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): <|fim_middle|> SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): <|fim_middle|> def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line))
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): <|fim_middle|> def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1)
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): <|fim_middle|> def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): <|fim_middle|> def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
return GoThriftGenLibrary
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): <|fim_middle|> @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
return isinstance(target, GoThriftLibrary)
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): <|fim_middle|> def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): <|fim_middle|> @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir)
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): <|fim_middle|> def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
return ['go']
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): <|fim_middle|> @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
self._generate_thrift(target, target_workdir)
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): <|fim_middle|> def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
"""Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides']
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): <|fim_middle|> <|fim▁end|>
all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep))
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: <|fim_middle|> return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
raise TaskError('Thrift file {} must contain "namespace go "', source)
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): <|fim_middle|> return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
return self._service_deps
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: <|fim_middle|> else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
gen_options += ',' + thrift_import
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: <|fim_middle|> cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
gen_options = thrift_import
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: <|fim_middle|> if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
cmd.append('-strict')
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': <|fim_middle|> return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
cmd.append('-verbose')
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: <|fim_middle|> source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target)
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: <|fim_middle|> gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result))
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def <|fim_middle|>(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
register_options
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def <|fim_middle|>(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
subsystem_dependencies
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def <|fim_middle|>(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
_thrift_binary
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def <|fim_middle|>(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
_deps
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def <|fim_middle|>(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
_service_deps
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def <|fim_middle|>(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
_declares_service
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def <|fim_middle|>(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
_get_go_namespace
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def <|fim_middle|>(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
synthetic_target_extra_dependencies
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def <|fim_middle|>(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
synthetic_target_type
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def <|fim_middle|>(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
is_gentarget
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def <|fim_middle|>(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
_thrift_cmd
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def <|fim_middle|>(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
_generate_thrift
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def <|fim_middle|>(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
product_types
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def <|fim_middle|>(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
execute_codegen
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def <|fim_middle|>(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def synthetic_target_dir(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
_copy_target_attributes
<|file_name|>go_thrift_gen.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import re import subprocess from pants.backend.codegen.subsystems.thrift_defaults import ThriftDefaults from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.workunit import WorkUnitLabel from pants.binaries.thrift_binary import ThriftBinary from pants.task.simple_codegen_task import SimpleCodegenTask from pants.util.dirutil import safe_mkdir from pants.util.memo import memoized_property from twitter.common.collections import OrderedSet from pants.contrib.go.targets.go_thrift_library import GoThriftGenLibrary, GoThriftLibrary class GoThriftGen(SimpleCodegenTask): @classmethod def register_options(cls, register): super(GoThriftGen, cls).register_options(register) register('--strict', default=True, fingerprint=True, type=bool, help='Run thrift compiler with strict warnings.') register('--gen-options', advanced=True, fingerprint=True, help='Use these apache thrift go gen options.') register('--thrift-import', advanced=True, help='Use this thrift-import gen option to thrift.') register('--thrift-import-target', advanced=True, help='Use this thrift import on symbolic defs.') @classmethod def subsystem_dependencies(cls): return (super(GoThriftGen, cls).subsystem_dependencies() + (ThriftDefaults, ThriftBinary.Factory.scoped(cls))) @memoized_property def _thrift_binary(self): thrift_binary = ThriftBinary.Factory.scoped_instance(self).create() return thrift_binary.path @memoized_property def _deps(self): thrift_import_target = self.get_options().thrift_import_target thrift_imports = self.context.resolve(thrift_import_target) return thrift_imports @memoized_property def _service_deps(self): service_deps = self.get_options().get('service_deps') return list(self.resolve_deps(service_deps)) if service_deps else self._deps SERVICE_PARSER = re.compile(r'^\s*service\s+(?:[^\s{]+)') NAMESPACE_PARSER = re.compile(r'^\s*namespace go\s+([^\s]+)', re.MULTILINE) def _declares_service(self, source): with open(source) as thrift: return any(line for line in thrift if self.SERVICE_PARSER.search(line)) def _get_go_namespace(self, source): with open(source) as thrift: namespace = self.NAMESPACE_PARSER.search(thrift.read()) if not namespace: raise TaskError('Thrift file {} must contain "namespace go "', source) return namespace.group(1) def synthetic_target_extra_dependencies(self, target, target_workdir): for source in target.sources_relative_to_buildroot(): if self._declares_service(os.path.join(get_buildroot(), source)): return self._service_deps return self._deps def synthetic_target_type(self, target): return GoThriftGenLibrary def is_gentarget(self, target): return isinstance(target, GoThriftLibrary) @memoized_property def _thrift_cmd(self): cmd = [self._thrift_binary] thrift_import = 'thrift_import={}'.format(self.get_options().thrift_import) gen_options = self.get_options().gen_options if gen_options: gen_options += ',' + thrift_import else: gen_options = thrift_import cmd.extend(('--gen', 'go:{}'.format(gen_options))) if self.get_options().strict: cmd.append('-strict') if self.get_options().level == 'debug': cmd.append('-verbose') return cmd def _generate_thrift(self, target, target_workdir): target_cmd = self._thrift_cmd[:] bases = OrderedSet(tgt.target_base for tgt in target.closure() if self.is_gentarget(tgt)) for base in bases: target_cmd.extend(('-I', base)) target_cmd.extend(('-o', target_workdir)) all_sources = list(target.sources_relative_to_buildroot()) if len(all_sources) != 1: raise TaskError('go_thrift_library only supports a single .thrift source file for {}.', target) source = all_sources[0] target_cmd.append(os.path.join(get_buildroot(), source)) with self.context.new_workunit(name=source, labels=[WorkUnitLabel.TOOL], cmd=' '.join(target_cmd)) as workunit: result = subprocess.call(target_cmd, stdout=workunit.output('stdout'), stderr=workunit.output('stderr')) if result != 0: raise TaskError('{} ... exited non-zero ({})'.format(self._thrift_binary, result)) gen_dir = os.path.join(target_workdir, 'gen-go') src_dir = os.path.join(target_workdir, 'src') safe_mkdir(src_dir) go_dir = os.path.join(target_workdir, 'src', 'go') os.rename(gen_dir, go_dir) @classmethod def product_types(cls): return ['go'] def execute_codegen(self, target, target_workdir): self._generate_thrift(target, target_workdir) @property def _copy_target_attributes(self): """Override `_copy_target_attributes` to exclude `provides`.""" return [a for a in super(GoThriftGen, self)._copy_target_attributes if a != 'provides'] def <|fim_middle|>(self, target, target_workdir): all_sources = list(target.sources_relative_to_buildroot()) source = all_sources[0] namespace = self._get_go_namespace(source) return os.path.join(target_workdir, 'src', 'go', namespace.replace(".", os.path.sep)) <|fim▁end|>
synthetic_target_dir
<|file_name|>test_blog_settings.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies and Contributors<|fim▁hole|># See license.txt from __future__ import unicode_literals # import frappe import unittest class TestBlogSettings(unittest.TestCase): pass<|fim▁end|>
<|file_name|>test_blog_settings.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest class TestBlogSettings(unittest.TestCase): <|fim_middle|> <|fim▁end|>
pass
<|file_name|>cache.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from cachy import CacheManager from cachy.serializers import PickleSerializer class Cache(CacheManager): _serializers = { 'pickle': PickleSerializer()<|fim▁hole|><|fim▁end|>
}
<|file_name|>cache.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from cachy import CacheManager from cachy.serializers import PickleSerializer class Cache(CacheManager): <|fim_middle|> <|fim▁end|>
_serializers = { 'pickle': PickleSerializer() }
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items<|fim▁hole|> appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait()<|fim▁end|>
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): <|fim_middle|> def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): <|fim_middle|> def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): <|fim_middle|> def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): <|fim_middle|> appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): <|fim_middle|> appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
app_lock.signal()
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): <|fim_middle|> #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current())
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': <|fim_middle|> fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
continue
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def <|fim_middle|>(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
__init__
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def <|fim_middle|>(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
get_drinker_list
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def <|fim_middle|>(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
get_listbox_items
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def <|fim_middle|>(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def handle_selection(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
quit
<|file_name|>client.py<|end_file_name|><|fim▁begin|>import urllib2 import appuifw, e32 from key_codes import * class Drinker(object): def __init__(self): self.id = 0 self.name = "" self.prom = 0.0 self.idle = "" self.drinks = 0 def get_drinker_list(): data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n") drinkers = [] for data_row in data: if data_row == '': continue fields = data_row.split('|') drinker = Drinker() drinker.id = int(fields[0]) drinker.name = fields[1] drinker.drinks = int(fields[2]) drinker.prom = float(fields[3]) drinker.idle = fields[4] drinkers.append(drinker) return drinkers def get_listbox_items(drinkers): items = [] for drinker in drinkers: items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle))) return items appuifw.app.title = u"Alkoholilaskuri" app_lock = e32.Ao_lock() #Define the exit function def quit(): app_lock.signal() appuifw.app.exit_key_handler = quit drinkers = get_drinker_list() items = get_listbox_items(drinkers) #Define a function that is called when an item is selected def <|fim_middle|>(): selected_drinker = drinkers[lb.current()] urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id)) appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info') new_drinkers = get_drinker_list() items = get_listbox_items(new_drinkers) lb.set_list(items, lb.current()) #Create an instance of Listbox and set it as the application's body lb = appuifw.Listbox(items, handle_selection) appuifw.app.body = lb app_lock.wait() <|fim▁end|>
handle_selection
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>''' salt.utils ~~~~~~~~~~ ''' <|fim▁hole|>class lazy_property(object): ''' meant to be used for lazy evaluation of an object attribute. property should represent non-mutable data, as it replaces itself. http://stackoverflow.com/a/6849299/564003 ''' def __init__(self, fget): self.fget = fget self.func_name = fget.__name__ def __get__(self, obj, cls): if obj is None: return None value = self.fget(obj) setattr(obj, self.func_name, value) return value<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>''' salt.utils ~~~~~~~~~~ ''' class lazy_property(object): <|fim_middle|> <|fim▁end|>
''' meant to be used for lazy evaluation of an object attribute. property should represent non-mutable data, as it replaces itself. http://stackoverflow.com/a/6849299/564003 ''' def __init__(self, fget): self.fget = fget self.func_name = fget.__name__ def __get__(self, obj, cls): if obj is None: return None value = self.fget(obj) setattr(obj, self.func_name, value) return value
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>''' salt.utils ~~~~~~~~~~ ''' class lazy_property(object): ''' meant to be used for lazy evaluation of an object attribute. property should represent non-mutable data, as it replaces itself. http://stackoverflow.com/a/6849299/564003 ''' def __init__(self, fget): <|fim_middle|> def __get__(self, obj, cls): if obj is None: return None value = self.fget(obj) setattr(obj, self.func_name, value) return value <|fim▁end|>
self.fget = fget self.func_name = fget.__name__
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>''' salt.utils ~~~~~~~~~~ ''' class lazy_property(object): ''' meant to be used for lazy evaluation of an object attribute. property should represent non-mutable data, as it replaces itself. http://stackoverflow.com/a/6849299/564003 ''' def __init__(self, fget): self.fget = fget self.func_name = fget.__name__ def __get__(self, obj, cls): <|fim_middle|> <|fim▁end|>
if obj is None: return None value = self.fget(obj) setattr(obj, self.func_name, value) return value
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>''' salt.utils ~~~~~~~~~~ ''' class lazy_property(object): ''' meant to be used for lazy evaluation of an object attribute. property should represent non-mutable data, as it replaces itself. http://stackoverflow.com/a/6849299/564003 ''' def __init__(self, fget): self.fget = fget self.func_name = fget.__name__ def __get__(self, obj, cls): if obj is None: <|fim_middle|> value = self.fget(obj) setattr(obj, self.func_name, value) return value <|fim▁end|>
return None
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>''' salt.utils ~~~~~~~~~~ ''' class lazy_property(object): ''' meant to be used for lazy evaluation of an object attribute. property should represent non-mutable data, as it replaces itself. http://stackoverflow.com/a/6849299/564003 ''' def <|fim_middle|>(self, fget): self.fget = fget self.func_name = fget.__name__ def __get__(self, obj, cls): if obj is None: return None value = self.fget(obj) setattr(obj, self.func_name, value) return value <|fim▁end|>
__init__
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>''' salt.utils ~~~~~~~~~~ ''' class lazy_property(object): ''' meant to be used for lazy evaluation of an object attribute. property should represent non-mutable data, as it replaces itself. http://stackoverflow.com/a/6849299/564003 ''' def __init__(self, fget): self.fget = fget self.func_name = fget.__name__ def <|fim_middle|>(self, obj, cls): if obj is None: return None value = self.fget(obj) setattr(obj, self.func_name, value) return value <|fim▁end|>
__get__
<|file_name|>solution.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import re a = [[0 for x in range(25)] for y in range(13)] f=open("../distrib/spiral.txt","r") s=f.readline().strip() dx, dy = [0, 1, 0, -1], [1, 0, -1, 0] x, y, c = 0, -1, 1 l=0 for i in range(13+13-1): if i%2==0: for j in range((25+25-i)//2): x += dx[i % 4] y += dy[i % 4] #print(x,y,l) a[x][y] = s[l] l=l+1 c += 1 else: for j in range((13+13-i)//2):<|fim▁hole|> y += dy[i % 4] #print(x,y,l) a[x][y] = s[l] l=l+1 c += 1 for i in a: for k in i: k=re.sub(r"¦","█",k) k=re.sub(r"¯","▀",k) k=re.sub(r"_","▄",k) print(k,end="") print()<|fim▁end|>
x += dx[i % 4]
<|file_name|>solution.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import re a = [[0 for x in range(25)] for y in range(13)] f=open("../distrib/spiral.txt","r") s=f.readline().strip() dx, dy = [0, 1, 0, -1], [1, 0, -1, 0] x, y, c = 0, -1, 1 l=0 for i in range(13+13-1): if i%2==0: <|fim_middle|> else: for j in range((13+13-i)//2): x += dx[i % 4] y += dy[i % 4] #print(x,y,l) a[x][y] = s[l] l=l+1 c += 1 for i in a: for k in i: k=re.sub(r"¦","█",k) k=re.sub(r"¯","▀",k) k=re.sub(r"_","▄",k) print(k,end="") print() <|fim▁end|>
for j in range((25+25-i)//2): x += dx[i % 4] y += dy[i % 4] #print(x,y,l) a[x][y] = s[l] l=l+1 c += 1
<|file_name|>solution.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 import re a = [[0 for x in range(25)] for y in range(13)] f=open("../distrib/spiral.txt","r") s=f.readline().strip() dx, dy = [0, 1, 0, -1], [1, 0, -1, 0] x, y, c = 0, -1, 1 l=0 for i in range(13+13-1): if i%2==0: for j in range((25+25-i)//2): x += dx[i % 4] y += dy[i % 4] #print(x,y,l) a[x][y] = s[l] l=l+1 c += 1 else: <|fim_middle|> for i in a: for k in i: k=re.sub(r"¦","█",k) k=re.sub(r"¯","▀",k) k=re.sub(r"_","▄",k) print(k,end="") print() <|fim▁end|>
for j in range((13+13-i)//2): x += dx[i % 4] y += dy[i % 4] #print(x,y,l) a[x][y] = s[l] l=l+1 c += 1
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'mwn' import os import sys import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template app = Flask(__name__) app.config.from_object('config') handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) ######################## # Configure Secret Key # ######################## def install_secret_key(app, filename='secret_key'): """Configure the SECRET_KEY from a file in the instance directory. If the file does not exist, print instructions<|fim▁hole|> try: app.config['SECRET_KEY'] = open(filename, 'rb').read() except IOError: print('Error: No secret key. Create it with:') full_path = os.path.dirname(filename) if not os.path.isdir(full_path): print('mkdir -p {filename}'.format(filename=full_path)) print('head -c 24 /dev/urandom > {filename}'.format(filename=filename)) sys.exit(1) if not app.config['DEBUG']: install_secret_key(app) @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 @app.after_request def after_request(response): response.headers.add('X-Test', 'This is only test.') response.headers.add('Access-Control-Allow-Origin', '*') # TODO: set to real origin return response from app.web.controller import webBp app.register_blueprint(webBp) from app.rest.controller import restBp app.register_blueprint(restBp)<|fim▁end|>
to create it from a shell with a random key, then exit. """ filename = os.path.join(app.instance_path, filename)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'mwn' import os import sys import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template app = Flask(__name__) app.config.from_object('config') handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) ######################## # Configure Secret Key # ######################## def install_secret_key(app, filename='secret_key'): <|fim_middle|> if not app.config['DEBUG']: install_secret_key(app) @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 @app.after_request def after_request(response): response.headers.add('X-Test', 'This is only test.') response.headers.add('Access-Control-Allow-Origin', '*') # TODO: set to real origin return response from app.web.controller import webBp app.register_blueprint(webBp) from app.rest.controller import restBp app.register_blueprint(restBp) <|fim▁end|>
"""Configure the SECRET_KEY from a file in the instance directory. If the file does not exist, print instructions to create it from a shell with a random key, then exit. """ filename = os.path.join(app.instance_path, filename) try: app.config['SECRET_KEY'] = open(filename, 'rb').read() except IOError: print('Error: No secret key. Create it with:') full_path = os.path.dirname(filename) if not os.path.isdir(full_path): print('mkdir -p {filename}'.format(filename=full_path)) print('head -c 24 /dev/urandom > {filename}'.format(filename=filename)) sys.exit(1)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'mwn' import os import sys import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template app = Flask(__name__) app.config.from_object('config') handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) ######################## # Configure Secret Key # ######################## def install_secret_key(app, filename='secret_key'): """Configure the SECRET_KEY from a file in the instance directory. If the file does not exist, print instructions to create it from a shell with a random key, then exit. """ filename = os.path.join(app.instance_path, filename) try: app.config['SECRET_KEY'] = open(filename, 'rb').read() except IOError: print('Error: No secret key. Create it with:') full_path = os.path.dirname(filename) if not os.path.isdir(full_path): print('mkdir -p {filename}'.format(filename=full_path)) print('head -c 24 /dev/urandom > {filename}'.format(filename=filename)) sys.exit(1) if not app.config['DEBUG']: install_secret_key(app) @app.errorhandler(404) def not_found(error): <|fim_middle|> @app.after_request def after_request(response): response.headers.add('X-Test', 'This is only test.') response.headers.add('Access-Control-Allow-Origin', '*') # TODO: set to real origin return response from app.web.controller import webBp app.register_blueprint(webBp) from app.rest.controller import restBp app.register_blueprint(restBp) <|fim▁end|>
return render_template('404.html'), 404
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'mwn' import os import sys import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template app = Flask(__name__) app.config.from_object('config') handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) ######################## # Configure Secret Key # ######################## def install_secret_key(app, filename='secret_key'): """Configure the SECRET_KEY from a file in the instance directory. If the file does not exist, print instructions to create it from a shell with a random key, then exit. """ filename = os.path.join(app.instance_path, filename) try: app.config['SECRET_KEY'] = open(filename, 'rb').read() except IOError: print('Error: No secret key. Create it with:') full_path = os.path.dirname(filename) if not os.path.isdir(full_path): print('mkdir -p {filename}'.format(filename=full_path)) print('head -c 24 /dev/urandom > {filename}'.format(filename=filename)) sys.exit(1) if not app.config['DEBUG']: install_secret_key(app) @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 @app.after_request def after_request(response): <|fim_middle|> from app.web.controller import webBp app.register_blueprint(webBp) from app.rest.controller import restBp app.register_blueprint(restBp) <|fim▁end|>
response.headers.add('X-Test', 'This is only test.') response.headers.add('Access-Control-Allow-Origin', '*') # TODO: set to real origin return response
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'mwn' import os import sys import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template app = Flask(__name__) app.config.from_object('config') handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) ######################## # Configure Secret Key # ######################## def install_secret_key(app, filename='secret_key'): """Configure the SECRET_KEY from a file in the instance directory. If the file does not exist, print instructions to create it from a shell with a random key, then exit. """ filename = os.path.join(app.instance_path, filename) try: app.config['SECRET_KEY'] = open(filename, 'rb').read() except IOError: print('Error: No secret key. Create it with:') full_path = os.path.dirname(filename) if not os.path.isdir(full_path): <|fim_middle|> print('head -c 24 /dev/urandom > {filename}'.format(filename=filename)) sys.exit(1) if not app.config['DEBUG']: install_secret_key(app) @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 @app.after_request def after_request(response): response.headers.add('X-Test', 'This is only test.') response.headers.add('Access-Control-Allow-Origin', '*') # TODO: set to real origin return response from app.web.controller import webBp app.register_blueprint(webBp) from app.rest.controller import restBp app.register_blueprint(restBp) <|fim▁end|>
print('mkdir -p {filename}'.format(filename=full_path))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'mwn' import os import sys import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template app = Flask(__name__) app.config.from_object('config') handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) ######################## # Configure Secret Key # ######################## def install_secret_key(app, filename='secret_key'): """Configure the SECRET_KEY from a file in the instance directory. If the file does not exist, print instructions to create it from a shell with a random key, then exit. """ filename = os.path.join(app.instance_path, filename) try: app.config['SECRET_KEY'] = open(filename, 'rb').read() except IOError: print('Error: No secret key. Create it with:') full_path = os.path.dirname(filename) if not os.path.isdir(full_path): print('mkdir -p {filename}'.format(filename=full_path)) print('head -c 24 /dev/urandom > {filename}'.format(filename=filename)) sys.exit(1) if not app.config['DEBUG']: <|fim_middle|> @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 @app.after_request def after_request(response): response.headers.add('X-Test', 'This is only test.') response.headers.add('Access-Control-Allow-Origin', '*') # TODO: set to real origin return response from app.web.controller import webBp app.register_blueprint(webBp) from app.rest.controller import restBp app.register_blueprint(restBp) <|fim▁end|>
install_secret_key(app)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'mwn' import os import sys import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template app = Flask(__name__) app.config.from_object('config') handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) ######################## # Configure Secret Key # ######################## def <|fim_middle|>(app, filename='secret_key'): """Configure the SECRET_KEY from a file in the instance directory. If the file does not exist, print instructions to create it from a shell with a random key, then exit. """ filename = os.path.join(app.instance_path, filename) try: app.config['SECRET_KEY'] = open(filename, 'rb').read() except IOError: print('Error: No secret key. Create it with:') full_path = os.path.dirname(filename) if not os.path.isdir(full_path): print('mkdir -p {filename}'.format(filename=full_path)) print('head -c 24 /dev/urandom > {filename}'.format(filename=filename)) sys.exit(1) if not app.config['DEBUG']: install_secret_key(app) @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 @app.after_request def after_request(response): response.headers.add('X-Test', 'This is only test.') response.headers.add('Access-Control-Allow-Origin', '*') # TODO: set to real origin return response from app.web.controller import webBp app.register_blueprint(webBp) from app.rest.controller import restBp app.register_blueprint(restBp) <|fim▁end|>
install_secret_key
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'mwn' import os import sys import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template app = Flask(__name__) app.config.from_object('config') handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) ######################## # Configure Secret Key # ######################## def install_secret_key(app, filename='secret_key'): """Configure the SECRET_KEY from a file in the instance directory. If the file does not exist, print instructions to create it from a shell with a random key, then exit. """ filename = os.path.join(app.instance_path, filename) try: app.config['SECRET_KEY'] = open(filename, 'rb').read() except IOError: print('Error: No secret key. Create it with:') full_path = os.path.dirname(filename) if not os.path.isdir(full_path): print('mkdir -p {filename}'.format(filename=full_path)) print('head -c 24 /dev/urandom > {filename}'.format(filename=filename)) sys.exit(1) if not app.config['DEBUG']: install_secret_key(app) @app.errorhandler(404) def <|fim_middle|>(error): return render_template('404.html'), 404 @app.after_request def after_request(response): response.headers.add('X-Test', 'This is only test.') response.headers.add('Access-Control-Allow-Origin', '*') # TODO: set to real origin return response from app.web.controller import webBp app.register_blueprint(webBp) from app.rest.controller import restBp app.register_blueprint(restBp) <|fim▁end|>
not_found
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>__author__ = 'mwn' import os import sys import logging from logging.handlers import RotatingFileHandler from flask import Flask, render_template app = Flask(__name__) app.config.from_object('config') handler = RotatingFileHandler('yapki.log', maxBytes=10000, backupCount=1) handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) ######################## # Configure Secret Key # ######################## def install_secret_key(app, filename='secret_key'): """Configure the SECRET_KEY from a file in the instance directory. If the file does not exist, print instructions to create it from a shell with a random key, then exit. """ filename = os.path.join(app.instance_path, filename) try: app.config['SECRET_KEY'] = open(filename, 'rb').read() except IOError: print('Error: No secret key. Create it with:') full_path = os.path.dirname(filename) if not os.path.isdir(full_path): print('mkdir -p {filename}'.format(filename=full_path)) print('head -c 24 /dev/urandom > {filename}'.format(filename=filename)) sys.exit(1) if not app.config['DEBUG']: install_secret_key(app) @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 @app.after_request def <|fim_middle|>(response): response.headers.add('X-Test', 'This is only test.') response.headers.add('Access-Control-Allow-Origin', '*') # TODO: set to real origin return response from app.web.controller import webBp app.register_blueprint(webBp) from app.rest.controller import restBp app.register_blueprint(restBp) <|fim▁end|>
after_request
<|file_name|>vectores.py<|end_file_name|><|fim▁begin|>from vectores_oo import Vector x = input('vector U componente X= ') y = input('vector U componente X= ') U = Vector(x,y) m = input('vector V magnitud= ') a = input('vector V angulo= ') V = Vector(m=m, a=a) E = input('Escalar= ') print "U=%s" % U<|fim▁hole|> print 'UxE=%s' % U.x_escalar(E) print 'VxE=%s' % V.x_escalar(E) print 'U+V=%s' % U.Suma(V) print 'U.V=%s' % U.ProductoPunto(V) print '|UxV|=%s' % U.Modulo_ProductoCruz(V)<|fim▁end|>
print "V=%s" % V
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ <|fim▁hole|> if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch()<|fim▁end|>
response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response:
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): <|fim_middle|> def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
""" Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): <|fim_middle|> class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
""" Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): <|fim_middle|> class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
""" Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): <|fim_middle|> def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
self.destination = destination self.custom_text = custom_text
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): <|fim_middle|> class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
""" Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): <|fim_middle|> class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
""" Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): <|fim_middle|> def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
self.destination = destination
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): <|fim_middle|> class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
""" Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): <|fim_middle|> if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
""" Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5)
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): <|fim_middle|> @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
self.d1_status = "" self.alert_list = alert_list
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): <|fim_middle|> def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
""" Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): <|fim_middle|> def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
""" :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text)
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): <|fim_middle|> if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
""" Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5)
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: <|fim_middle|> else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED"
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed <|fim_middle|> else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
status = "CLOSED"
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open <|fim_middle|> return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
status = "OPEN"
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: <|fim_middle|> time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch()
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: <|fim_middle|> else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
CUSTOM_TEXT = sys.argv[2]
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: <|fim_middle|> if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
CUSTOM_TEXT = "WR31 Door"
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: <|fim_middle|> MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT))
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def <|fim_middle|>(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
millisecond_timestamp
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def <|fim_middle|>(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
cli_command
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def <|fim_middle|>(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def send_alert(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
__init__
<|file_name|>doormon.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2016 Digi International Inc. All Rights Reserved. """ Monitor the WR31 door enclosure """ import time import sys import sarcli import idigidata def millisecond_timestamp(): """ Return a timestamp, in milliseconds :return ms_timestamp: int, Timestamp in milliseconds """ ms_timestamp = int(time.time() * 1000) return ms_timestamp def cli_command(cmd): """ Send a command to the SarOS CLI and receive the response :param cmd: str, Command to run :return response: str, Response to cmd """ cli = sarcli.open() cli.write(cmd) response = cli.read() cli.close() return response class SmsAlert(object): """ Send an SMS alert """ def __init__(self, destination, custom_text): self.destination = destination self.custom_text = custom_text def <|fim_middle|>(self, message): """ Send an SMS alert :param message: str, Content of SMS message :return response: str, Response to sendsms command """ message = "{0}: {1}".format(self.custom_text, message) command = 'sendsms ' + self.destination + ' "' + message + '" ' response = cli_command(command) return response class DatapointAlert(object): """ Send a Datapoint alert """ def __init__(self, destination): self.destination = destination def send_alert(self, message): """ Send a Datapoint alert :param message: str, Datapoint content :return response: tuple, Result code of datapoint upload attempt """ timestamp = millisecond_timestamp() dpoint = """\ <DataPoint> <dataType>STRING</dataType> <data>{0}</data> <timestamp>{1}</timestamp> <streamId>{2}</streamId> </DataPoint>""".format(message, timestamp, self.destination) response = idigidata.send_to_idigi(dpoint, "DataPoint/stream.xml") return response class DoorMonitor(object): """ Provides methods to monitor the enclosure door status """ def __init__(self, alert_list): self.d1_status = "" self.alert_list = alert_list @classmethod def switch_status(cls): """ Reads line status and sends an alert if the status is different :return status: str, Door status, "OPEN" or "CLOSED" """ response = cli_command("gpio dio") if "D1: DOUT=OFF, DIN=LOW" in response: if not "D0: DOUT=ON" in response: # Door is closed status = "CLOSED" else: # Door is open status = "OPEN" return status def send_alert(self, text): """ :param text: str, Alert content :return: """ for alert in self.alert_list: alert.send_alert(text) def monitor_switch(self): """ Runs line monitoring and alerting in a loop :return: """ while True: status = self.switch_status() if status != self.d1_status: print "WR31 door is: {0}".format(status) self.send_alert(status) self.d1_status = status time.sleep(.5) if __name__ == '__main__': ALERT_FUNCTIONS = [DatapointAlert("WR31_door")] if len(sys.argv) >= 3: CUSTOM_TEXT = sys.argv[2] else: CUSTOM_TEXT = "WR31 Door" if len(sys.argv) >= 2: ALERT_FUNCTIONS.append(SmsAlert(sys.argv[1], CUSTOM_TEXT)) MONITOR = DoorMonitor(ALERT_FUNCTIONS) MONITOR.monitor_switch() <|fim▁end|>
send_alert