os_family_impl.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. '''
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. '''
  16. import types
  17. from os_check import OSCheck
  18. class OsFamilyImpl(object):
  19. """
  20. Base class for os depended factory. Usage::
  21. class BaseFoo(object): pass
  22. @Factory("windows")
  23. class OsFoo(object):pass
  24. print BaseFoo()# OsFoo
  25. """
  26. DEFAULT = "default"
  27. """
  28. constant for default implementation
  29. """
  30. def __init__(self, base_cls=None, os_family=None):
  31. self.base_cls = base_cls
  32. self.os_const = os_family
  33. def __call__(self, cls):
  34. if self.base_cls:
  35. base_cls = self.base_cls
  36. else:
  37. base_cls = cls.__bases__[0]
  38. if not hasattr(base_cls, "_impls"):
  39. base_cls._impls = {}
  40. base_cls._impls[self.os_const] = cls
  41. def new(cls, *args, **kwargs):
  42. if OSCheck.get_os_family() in cls._impls:
  43. os_impl_cls = cls._impls[OSCheck.get_os_family()]
  44. else:
  45. os_impl_cls = cls._impls[OsFamilyImpl.DEFAULT]
  46. return object.__new__(os_impl_cls)
  47. base_cls.__new__ = types.MethodType(new, base_cls)
  48. return cls