Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

settings.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. """isort/settings.py.
  2. Defines how the default settings for isort should be loaded
  3. (First from the default setting dictionary at the top of the file, then overridden by any settings
  4. in ~/.isort.cfg if there are any)
  5. Copyright (C) 2013 Timothy Edmund Crosley
  6. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
  7. documentation files (the "Software"), to deal in the Software without restriction, including without limitation
  8. the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  9. to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in all copies or
  11. substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  13. TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  14. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  15. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  16. OTHER DEALINGS IN THE SOFTWARE.
  17. """
  18. from __future__ import absolute_import, division, print_function, unicode_literals
  19. import fnmatch
  20. import io
  21. import os
  22. import posixpath
  23. import sys
  24. from collections import namedtuple
  25. from .pie_slice import itemsview, lru_cache, native_str
  26. try:
  27. import configparser
  28. except ImportError:
  29. import ConfigParser as configparser
  30. MAX_CONFIG_SEARCH_DEPTH = 25 # The number of parent directories isort will look for a config file within
  31. DEFAULT_SECTIONS = ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER')
  32. WrapModes = ('GRID', 'VERTICAL', 'HANGING_INDENT', 'VERTICAL_HANGING_INDENT', 'VERTICAL_GRID', 'VERTICAL_GRID_GROUPED',
  33. 'VERTICAL_GRID_GROUPED_NO_COMMA', 'NOQA')
  34. WrapModes = namedtuple('WrapModes', WrapModes)(*range(len(WrapModes)))
  35. # Note that none of these lists must be complete as they are simply fallbacks for when included auto-detection fails.
  36. default = {'force_to_top': [],
  37. 'skip': ['__init__.py', ],
  38. 'skip_glob': [],
  39. 'line_length': 79,
  40. 'wrap_length': 0,
  41. 'line_ending': None,
  42. 'sections': DEFAULT_SECTIONS,
  43. 'no_sections': False,
  44. 'known_future_library': ['__future__'],
  45. 'known_standard_library': ['AL', 'BaseHTTPServer', 'Bastion', 'CGIHTTPServer', 'Carbon', 'ColorPicker',
  46. 'ConfigParser', 'Cookie', 'DEVICE', 'DocXMLRPCServer', 'EasyDialogs', 'FL',
  47. 'FrameWork', 'GL', 'HTMLParser', 'MacOS', 'MimeWriter', 'MiniAEFrame', 'Nav',
  48. 'PixMapWrapper', 'Queue', 'SUNAUDIODEV', 'ScrolledText', 'SimpleHTTPServer',
  49. 'SimpleXMLRPCServer', 'SocketServer', 'StringIO', 'Tix', 'Tkinter', 'UserDict',
  50. 'UserList', 'UserString', 'W', '__builtin__', 'abc', 'aepack', 'aetools',
  51. 'aetypes', 'aifc', 'al', 'anydbm', 'applesingle', 'argparse', 'array', 'ast',
  52. 'asynchat', 'asyncio', 'asyncore', 'atexit', 'audioop', 'autoGIL', 'base64',
  53. 'bdb', 'binascii', 'binhex', 'bisect', 'bsddb', 'buildtools', 'builtins',
  54. 'bz2', 'cPickle', 'cProfile', 'cStringIO', 'calendar', 'cd', 'cfmfile', 'cgi',
  55. 'cgitb', 'chunk', 'cmath', 'cmd', 'code', 'codecs', 'codeop', 'collections',
  56. 'colorsys', 'commands', 'compileall', 'compiler', 'concurrent', 'configparser',
  57. 'contextlib', 'cookielib', 'copy', 'copy_reg', 'copyreg', 'crypt', 'csv',
  58. 'ctypes', 'curses', 'datetime', 'dbhash', 'dbm', 'decimal', 'difflib',
  59. 'dircache', 'dis', 'distutils', 'dl', 'doctest', 'dumbdbm', 'dummy_thread',
  60. 'dummy_threading', 'email', 'encodings', 'ensurepip', 'enum', 'errno',
  61. 'exceptions', 'faulthandler', 'fcntl', 'filecmp', 'fileinput', 'findertools',
  62. 'fl', 'flp', 'fm', 'fnmatch', 'formatter', 'fpectl', 'fpformat', 'fractions',
  63. 'ftplib', 'functools', 'future_builtins', 'gc', 'gdbm', 'gensuitemodule',
  64. 'getopt', 'getpass', 'gettext', 'gl', 'glob', 'grp', 'gzip', 'hashlib',
  65. 'heapq', 'hmac', 'hotshot', 'html', 'htmlentitydefs', 'htmllib', 'http',
  66. 'httplib', 'ic', 'icopen', 'imageop', 'imaplib', 'imgfile', 'imghdr', 'imp',
  67. 'importlib', 'imputil', 'inspect', 'io', 'ipaddress', 'itertools', 'jpeg',
  68. 'json', 'keyword', 'lib2to3', 'linecache', 'locale', 'logging', 'lzma',
  69. 'macerrors', 'macostools', 'macpath', 'macresource', 'mailbox', 'mailcap',
  70. 'marshal', 'math', 'md5', 'mhlib', 'mimetools', 'mimetypes', 'mimify', 'mmap',
  71. 'modulefinder', 'msilib', 'msvcrt', 'multifile', 'multiprocessing', 'mutex',
  72. 'netrc', 'new', 'nis', 'nntplib', 'numbers', 'operator', 'optparse', 'os',
  73. 'ossaudiodev', 'parser', 'pathlib', 'pdb', 'pickle', 'pickletools', 'pipes',
  74. 'pkgutil', 'platform', 'plistlib', 'popen2', 'poplib', 'posix', 'posixfile',
  75. 'pprint', 'profile', 'pstats', 'pty', 'pwd', 'py_compile', 'pyclbr', 'pydoc',
  76. 'queue', 'quopri', 'random', 're', 'readline', 'reprlib', 'resource', 'rexec',
  77. 'rfc822', 'rlcompleter', 'robotparser', 'runpy', 'sched', 'secrets', 'select',
  78. 'selectors', 'sets', 'sgmllib', 'sha', 'shelve', 'shlex', 'shutil', 'signal',
  79. 'site', 'sitecustomize', 'smtpd', 'smtplib', 'sndhdr', 'socket', 'socketserver',
  80. 'spwd', 'sqlite3', 'ssl', 'stat', 'statistics', 'statvfs', 'string', 'stringprep',
  81. 'struct', 'subprocess', 'sunau', 'sunaudiodev', 'symbol', 'symtable', 'sys',
  82. 'sysconfig', 'syslog', 'tabnanny', 'tarfile', 'telnetlib', 'tempfile', 'termios',
  83. 'test', 'textwrap', 'this', 'thread', 'threading', 'time', 'timeit', 'tkinter',
  84. 'token', 'tokenize', 'trace', 'traceback', 'tracemalloc', 'ttk', 'tty', 'turtle',
  85. 'turtledemo', 'types', 'typing', 'unicodedata', 'unittest', 'urllib', 'urllib2',
  86. 'urlparse', 'user', 'usercustomize', 'uu', 'uuid', 'venv', 'videoreader',
  87. 'warnings', 'wave', 'weakref', 'webbrowser', 'whichdb', 'winreg', 'winsound',
  88. 'wsgiref', 'xdrlib', 'xml', 'xmlrpc', 'xmlrpclib', 'zipapp', 'zipfile',
  89. 'zipimport', 'zlib'],
  90. 'known_third_party': ['google.appengine.api'],
  91. 'known_first_party': [],
  92. 'multi_line_output': WrapModes.GRID,
  93. 'forced_separate': [],
  94. 'indent': ' ' * 4,
  95. 'comment_prefix': ' #',
  96. 'length_sort': False,
  97. 'add_imports': [],
  98. 'remove_imports': [],
  99. 'force_single_line': False,
  100. 'default_section': 'FIRSTPARTY',
  101. 'import_heading_future': '',
  102. 'import_heading_stdlib': '',
  103. 'import_heading_thirdparty': '',
  104. 'import_heading_firstparty': '',
  105. 'import_heading_localfolder': '',
  106. 'balanced_wrapping': False,
  107. 'use_parentheses': False,
  108. 'order_by_type': True,
  109. 'atomic': False,
  110. 'lines_after_imports': -1,
  111. 'lines_between_sections': 1,
  112. 'lines_between_types': 0,
  113. 'combine_as_imports': False,
  114. 'combine_star': False,
  115. 'keep_direct_and_as_imports': False,
  116. 'include_trailing_comma': False,
  117. 'from_first': False,
  118. 'verbose': False,
  119. 'quiet': False,
  120. 'force_adds': False,
  121. 'force_alphabetical_sort_within_sections': False,
  122. 'force_alphabetical_sort': False,
  123. 'force_grid_wrap': 0,
  124. 'force_sort_within_sections': False,
  125. 'show_diff': False,
  126. 'ignore_whitespace': False,
  127. 'no_lines_before': [],
  128. 'no_inline_sort': False}
  129. @lru_cache()
  130. def from_path(path):
  131. computed_settings = default.copy()
  132. _update_settings_with_config(path, '.editorconfig', '~/.editorconfig', ('*', '*.py', '**.py'), computed_settings)
  133. _update_settings_with_config(path, '.isort.cfg', '~/.isort.cfg', ('settings', 'isort'), computed_settings)
  134. _update_settings_with_config(path, 'setup.cfg', None, ('isort', ), computed_settings)
  135. _update_settings_with_config(path, 'tox.ini', None, ('isort', ), computed_settings)
  136. return computed_settings
  137. def _update_settings_with_config(path, name, default, sections, computed_settings):
  138. editor_config_file = default and os.path.expanduser(default)
  139. tries = 0
  140. current_directory = path
  141. while current_directory and tries < MAX_CONFIG_SEARCH_DEPTH:
  142. potential_path = os.path.join(current_directory, native_str(name))
  143. if os.path.exists(potential_path):
  144. editor_config_file = potential_path
  145. break
  146. new_directory = os.path.split(current_directory)[0]
  147. if current_directory == new_directory:
  148. break
  149. current_directory = new_directory
  150. tries += 1
  151. if editor_config_file and os.path.exists(editor_config_file):
  152. _update_with_config_file(editor_config_file, sections, computed_settings)
  153. def _update_with_config_file(file_path, sections, computed_settings):
  154. settings = _get_config_data(file_path, sections).copy()
  155. if not settings:
  156. return
  157. if file_path.endswith('.editorconfig'):
  158. indent_style = settings.pop('indent_style', '').strip()
  159. indent_size = settings.pop('indent_size', '').strip()
  160. if indent_style == 'space':
  161. computed_settings['indent'] = ' ' * (indent_size and int(indent_size) or 4)
  162. elif indent_style == 'tab':
  163. computed_settings['indent'] = '\t' * (indent_size and int(indent_size) or 1)
  164. max_line_length = settings.pop('max_line_length', '').strip()
  165. if max_line_length:
  166. computed_settings['line_length'] = float('inf') if max_line_length == 'off' else int(max_line_length)
  167. for key, value in itemsview(settings):
  168. access_key = key.replace('not_', '').lower()
  169. existing_value_type = type(default.get(access_key, ''))
  170. if existing_value_type in (list, tuple):
  171. # sections has fixed order values; no adding or substraction from any set
  172. if access_key == 'sections':
  173. computed_settings[access_key] = tuple(_as_list(value))
  174. else:
  175. existing_data = set(computed_settings.get(access_key, default.get(access_key)))
  176. if key.startswith('not_'):
  177. computed_settings[access_key] = list(existing_data.difference(_as_list(value)))
  178. else:
  179. computed_settings[access_key] = list(existing_data.union(_as_list(value)))
  180. elif existing_value_type == bool and value.lower().strip() == 'false':
  181. computed_settings[access_key] = False
  182. elif key.startswith('known_'):
  183. computed_settings[access_key] = list(_as_list(value))
  184. elif key == 'force_grid_wrap':
  185. try:
  186. result = existing_value_type(value)
  187. except ValueError:
  188. # backwards compat
  189. result = default.get(access_key) if value.lower().strip() == 'false' else 2
  190. computed_settings[access_key] = result
  191. else:
  192. computed_settings[access_key] = existing_value_type(value)
  193. def _as_list(value):
  194. return filter(bool, [item.strip() for item in value.replace('\n', ',').split(',')])
  195. @lru_cache()
  196. def _get_config_data(file_path, sections):
  197. with io.open(file_path, 'r') as config_file:
  198. if file_path.endswith('.editorconfig'):
  199. line = '\n'
  200. last_position = config_file.tell()
  201. while line:
  202. line = config_file.readline()
  203. if '[' in line:
  204. config_file.seek(last_position)
  205. break
  206. last_position = config_file.tell()
  207. if sys.version_info >= (3, 2):
  208. config = configparser.ConfigParser()
  209. config.read_file(config_file)
  210. else:
  211. config = configparser.SafeConfigParser()
  212. config.readfp(config_file)
  213. settings = {}
  214. for section in sections:
  215. if config.has_section(section):
  216. settings.update(dict(config.items(section)))
  217. return settings
  218. return {}
  219. def should_skip(filename, config, path='/'):
  220. """Returns True if the file should be skipped based on the passed in settings."""
  221. for skip_path in config['skip']:
  222. if posixpath.abspath(posixpath.join(path, filename)) == posixpath.abspath(skip_path.replace('\\', '/')):
  223. return True
  224. position = os.path.split(filename)
  225. while position[1]:
  226. if position[1] in config['skip']:
  227. return True
  228. position = os.path.split(position[0])
  229. for glob in config['skip_glob']:
  230. if fnmatch.fnmatch(filename, glob):
  231. return True
  232. return False