mlog.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # Copyright 2013-2014 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. import sys, os, platform
  12. """This is (mostly) a standalone module used to write logging
  13. information about Meson runs. Some output goes to screen,
  14. some to logging dir and some goes to both."""
  15. colorize_console = platform.system().lower() != 'windows' and os.isatty(sys.stdout.fileno())
  16. log_dir = None
  17. log_file = None
  18. def initialize(logdir):
  19. global log_dir, log_file
  20. log_dir = logdir
  21. log_file = open(os.path.join(logdir, 'meson-log.txt'), 'w')
  22. def shutdown():
  23. global log_file
  24. if log_file is not None:
  25. log_file.close()
  26. class AnsiDecorator():
  27. plain_code = "\033[0m"
  28. def __init__(self, text, code):
  29. self.text = text
  30. self.code = code
  31. def get_text(self, with_codes):
  32. if with_codes:
  33. return self.code + self.text + AnsiDecorator.plain_code
  34. return self.text
  35. def bold(text):
  36. return AnsiDecorator(text, "\033[1m")
  37. def red(text):
  38. return AnsiDecorator(text, "\033[1;31m")
  39. def green(text):
  40. return AnsiDecorator(text, "\033[1;32m")
  41. def cyan(text):
  42. return AnsiDecorator(text, "\033[1;36m")
  43. def process_markup(args, keep):
  44. arr = []
  45. for arg in args:
  46. if isinstance(arg, str):
  47. arr.append(arg)
  48. elif isinstance(arg, AnsiDecorator):
  49. arr.append(arg.get_text(keep))
  50. else:
  51. arr.append(str(arg))
  52. return arr
  53. def debug(*args, **kwargs):
  54. arr = process_markup(args, False)
  55. if log_file is not None:
  56. print(*arr, file=log_file, **kwargs) # Log file never gets ANSI codes.
  57. log_file.flush()
  58. def log(*args, **kwargs):
  59. arr = process_markup(args, False)
  60. if log_file is not None:
  61. print(*arr, file=log_file, **kwargs) # Log file never gets ANSI codes.
  62. log_file.flush()
  63. if colorize_console:
  64. arr = process_markup(args, True)
  65. print(*arr, **kwargs)