PageRenderTime 61ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/digits/config/edit.py

https://gitlab.com/sixsamuraisoldier/DIGITS
Python | 166 lines | 144 code | 11 blank | 11 comment | 13 complexity | 6303260416e2a71e9806d3baae0da2f0 MD5 | raw file
  1. #!/usr/bin/env python2
  2. # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
  3. from __future__ import absolute_import
  4. import argparse
  5. import os
  6. from . import config_file
  7. from . import config_option
  8. from . import current_config
  9. from . import prompt
  10. def print_config(verbose=False):
  11. """
  12. Prints out a matrix of config option values for each level
  13. """
  14. min_visibility = config_option.Visibility.DEFAULT
  15. if verbose:
  16. min_visibility = config_option.Visibility.HIDDEN
  17. levels = [('INSTANCE', config_file.InstanceConfigFile())]
  18. # filter out the files which don't exist
  19. levels = [l for l in levels if l[1].can_read()]
  20. if len(levels) == 0:
  21. # nothing to display
  22. return None
  23. # create a row for each option
  24. row_headers = []
  25. row_data = []
  26. for option in [o for o in current_config.option_list
  27. if o.visibility() >= min_visibility]:
  28. row_headers.append(option.prompt_title())
  29. row = []
  30. for title, config in levels:
  31. value = config.get(option.config_file_key())
  32. row.append(prompt.value_to_str(value))
  33. row_data.append(row)
  34. prompt.print_section_header('Current Config')
  35. # calculate the width of each column for pretty printing
  36. row_header_width = max([len(h) for h in row_headers])
  37. row_data_widths = []
  38. for i, level in enumerate(levels):
  39. title, config = level
  40. w = len(title)
  41. for row in row_data:
  42. if len(row[i]) > w:
  43. w = len(row[i])
  44. row_data_widths.append(w)
  45. # build the format string for printing
  46. row_format = '%%%ds' % row_header_width
  47. for width in row_data_widths:
  48. row_format += ' | %%-%ds' % width
  49. # print header row
  50. print row_format % (('',) + tuple([level[0] for level in levels]))
  51. # print option rows
  52. for i, row in enumerate(row_data):
  53. print row_format % ((row_headers[i],) + tuple(row))
  54. print
  55. def edit_config_file(verbose=False):
  56. """
  57. Prompt the user for which file to edit,
  58. then allow them to set options in that file
  59. """
  60. suggestions = []
  61. instanceConfig = config_file.InstanceConfigFile()
  62. if instanceConfig.can_write():
  63. suggestions.append(prompt.Suggestion(
  64. instanceConfig.filename(), 'I',
  65. desc = 'Instance', default=True))
  66. def filenameValidator(filename):
  67. """
  68. Returns True if this is a valid file to edit
  69. """
  70. if os.path.isfile(filename):
  71. if not os.access(filename, os.W_OK):
  72. raise config_option.BadValue('You do not have write permission')
  73. else:
  74. return filename
  75. if os.path.isdir(filename):
  76. raise config_option.BadValue('This is a directory')
  77. dirname = os.path.dirname(os.path.realpath(filename))
  78. if not os.path.isdir(dirname):
  79. raise config_option.BadValue('Path not found: %s' % dirname)
  80. elif not os.access(dirname, os.W_OK):
  81. raise config_option.BadValue('You do not have write permission')
  82. return filename
  83. filename = prompt.get_input(
  84. message = 'Which file do you want to edit?',
  85. suggestions = suggestions,
  86. validator = filenameValidator,
  87. is_path = True,
  88. )
  89. print 'Editing file at %s ...' % os.path.realpath(filename)
  90. print
  91. is_standard_location = False
  92. if filename == instanceConfig.filename():
  93. is_standard_location = True
  94. instanceConfig = None
  95. configFile = config_file.ConfigFile(filename)
  96. min_visibility = config_option.Visibility.DEFAULT
  97. if verbose:
  98. min_visibility = config_option.Visibility.HIDDEN
  99. # Loop through the visible options
  100. for option in [o for o in current_config.option_list
  101. if o.visibility() >= min_visibility]:
  102. previous_value = configFile.get(option.config_file_key())
  103. suggestions = [prompt.Suggestion(None, 'U',
  104. desc='unset', default=(previous_value is None))]
  105. if previous_value is not None:
  106. suggestions.append(prompt.Suggestion(previous_value, '',
  107. desc = 'Previous', default = True))
  108. if instanceConfig is not None:
  109. instance_value = instanceConfig.get(option.config_file_key())
  110. if instance_value is not None:
  111. suggestions.append(prompt.Suggestion(instance_value, 'I',
  112. desc = 'Instance', default = is_standard_location))
  113. suggestions += option.suggestions()
  114. if option.optional():
  115. suggestions.append(prompt.Suggestion('', 'N',
  116. desc = 'none', default = True))
  117. prompt.print_section_header(option.prompt_title())
  118. value = prompt.get_input(
  119. message = option.prompt_message(),
  120. validator = option.validate,
  121. suggestions = suggestions,
  122. is_path = option.is_path(),
  123. )
  124. print
  125. configFile.set(option.config_file_key(), value)
  126. configFile.save()
  127. print 'New config saved at %s' % configFile.filename()
  128. print
  129. print configFile
  130. if __name__ == '__main__':
  131. parser = argparse.ArgumentParser(description='Config - DIGITS')
  132. parser.add_argument('-v', '--verbose',
  133. action="store_true",
  134. help='view more options')
  135. args = vars(parser.parse_args())
  136. print_config(args['verbose'])
  137. edit_config_file(args['verbose'])