thebleep 4.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of thebleep might be problematic. Click here for more details.

Files changed (230) hide show
  1. thebleep/__init__.py +0 -0
  2. thebleep/__main__.py +16 -0
  3. thebleep/argument_parser.py +203 -0
  4. thebleep/cachefile.py +89 -0
  5. thebleep/conf.py +232 -0
  6. thebleep/const.py +170 -0
  7. thebleep/corrector.py +229 -0
  8. thebleep/entrypoints/__init__.py +0 -0
  9. thebleep/entrypoints/alias.py +60 -0
  10. thebleep/entrypoints/doctor.py +469 -0
  11. thebleep/entrypoints/fix_command.py +71 -0
  12. thebleep/entrypoints/main.py +92 -0
  13. thebleep/entrypoints/not_configured.py +112 -0
  14. thebleep/entrypoints/shell_logger.py +257 -0
  15. thebleep/exceptions.py +10 -0
  16. thebleep/explain.py +169 -0
  17. thebleep/logs.py +338 -0
  18. thebleep/output_readers/__init__.py +76 -0
  19. thebleep/output_readers/read_log.py +142 -0
  20. thebleep/output_readers/rerun.py +140 -0
  21. thebleep/output_readers/shell_logger.py +59 -0
  22. thebleep/replay.py +198 -0
  23. thebleep/rulepack.py +576 -0
  24. thebleep/rules/__init__.py +0 -0
  25. thebleep/rules/adb_unknown_command.py +54 -0
  26. thebleep/rules/ag_literal.py +10 -0
  27. thebleep/rules/apt_get.py +60 -0
  28. thebleep/rules/apt_get_search.py +14 -0
  29. thebleep/rules/apt_invalid_operation.py +63 -0
  30. thebleep/rules/apt_list_upgradable.py +16 -0
  31. thebleep/rules/apt_upgrade.py +16 -0
  32. thebleep/rules/aws_cli.py +17 -0
  33. thebleep/rules/az_cli.py +44 -0
  34. thebleep/rules/brew_cask_dependency.py +40 -0
  35. thebleep/rules/brew_install.py +35 -0
  36. thebleep/rules/brew_link.py +17 -0
  37. thebleep/rules/brew_reinstall.py +21 -0
  38. thebleep/rules/brew_uninstall.py +14 -0
  39. thebleep/rules/brew_unknown_command.py +88 -0
  40. thebleep/rules/brew_update_formula.py +12 -0
  41. thebleep/rules/cargo.py +6 -0
  42. thebleep/rules/cargo_no_command.py +21 -0
  43. thebleep/rules/cat_dir.py +14 -0
  44. thebleep/rules/cd_correction.py +53 -0
  45. thebleep/rules/cd_cs.py +21 -0
  46. thebleep/rules/cd_mkdir.py +24 -0
  47. thebleep/rules/cd_parent.py +16 -0
  48. thebleep/rules/chmod_x.py +61 -0
  49. thebleep/rules/choco_install.py +25 -0
  50. thebleep/rules/composer_not_command.py +40 -0
  51. thebleep/rules/conda_mistype.py +17 -0
  52. thebleep/rules/cp_create_destination.py +17 -0
  53. thebleep/rules/cp_omitting_directory.py +15 -0
  54. thebleep/rules/cpp11.py +12 -0
  55. thebleep/rules/dirty_untar.py +43 -0
  56. thebleep/rules/dirty_unzip.py +61 -0
  57. thebleep/rules/django_south_ghost.py +8 -0
  58. thebleep/rules/django_south_merge.py +8 -0
  59. thebleep/rules/dnf_no_such_command.py +37 -0
  60. thebleep/rules/docker_daemon_not_running.py +53 -0
  61. thebleep/rules/docker_image_being_used_by_container.py +21 -0
  62. thebleep/rules/docker_login.py +14 -0
  63. thebleep/rules/docker_not_command.py +91 -0
  64. thebleep/rules/dry.py +15 -0
  65. thebleep/rules/fab_command_not_found.py +38 -0
  66. thebleep/rules/fix_alt_space.py +15 -0
  67. thebleep/rules/fix_file.py +80 -0
  68. thebleep/rules/gem_unknown_command.py +41 -0
  69. thebleep/rules/git_add.py +27 -0
  70. thebleep/rules/git_add_force.py +13 -0
  71. thebleep/rules/git_bisect_usage.py +16 -0
  72. thebleep/rules/git_branch_0flag.py +27 -0
  73. thebleep/rules/git_branch_delete.py +13 -0
  74. thebleep/rules/git_branch_delete_checked_out.py +52 -0
  75. thebleep/rules/git_branch_exists.py +28 -0
  76. thebleep/rules/git_branch_list.py +14 -0
  77. thebleep/rules/git_checkout.py +61 -0
  78. thebleep/rules/git_clone_git_clone.py +12 -0
  79. thebleep/rules/git_clone_missing.py +42 -0
  80. thebleep/rules/git_commit_add.py +17 -0
  81. thebleep/rules/git_commit_amend.py +11 -0
  82. thebleep/rules/git_commit_reset.py +11 -0
  83. thebleep/rules/git_diff_no_index.py +16 -0
  84. thebleep/rules/git_diff_staged.py +13 -0
  85. thebleep/rules/git_dubious_ownership.py +26 -0
  86. thebleep/rules/git_fix_stash.py +37 -0
  87. thebleep/rules/git_flag_after_filename.py +31 -0
  88. thebleep/rules/git_help_aliased.py +12 -0
  89. thebleep/rules/git_hook_bypass.py +27 -0
  90. thebleep/rules/git_lfs_mistype.py +18 -0
  91. thebleep/rules/git_main_master.py +16 -0
  92. thebleep/rules/git_merge.py +18 -0
  93. thebleep/rules/git_merge_unrelated.py +12 -0
  94. thebleep/rules/git_not_command.py +18 -0
  95. thebleep/rules/git_pull.py +16 -0
  96. thebleep/rules/git_pull_clone.py +13 -0
  97. thebleep/rules/git_pull_uncommitted_changes.py +14 -0
  98. thebleep/rules/git_push.py +44 -0
  99. thebleep/rules/git_push_different_branch_names.py +12 -0
  100. thebleep/rules/git_push_force.py +18 -0
  101. thebleep/rules/git_push_pull.py +20 -0
  102. thebleep/rules/git_push_without_commits.py +12 -0
  103. thebleep/rules/git_rebase_merge_dir.py +17 -0
  104. thebleep/rules/git_rebase_no_changes.py +13 -0
  105. thebleep/rules/git_remote_delete.py +13 -0
  106. thebleep/rules/git_remote_seturl_add.py +12 -0
  107. thebleep/rules/git_rm_local_modifications.py +19 -0
  108. thebleep/rules/git_rm_recursive.py +16 -0
  109. thebleep/rules/git_rm_staged.py +19 -0
  110. thebleep/rules/git_stash.py +14 -0
  111. thebleep/rules/git_stash_pop.py +18 -0
  112. thebleep/rules/git_tag_force.py +13 -0
  113. thebleep/rules/git_two_dashes.py +14 -0
  114. thebleep/rules/go_run.py +16 -0
  115. thebleep/rules/go_unknown_command.py +28 -0
  116. thebleep/rules/gradle_no_task.py +39 -0
  117. thebleep/rules/gradle_wrapper.py +13 -0
  118. thebleep/rules/grep_arguments_order.py +23 -0
  119. thebleep/rules/grep_recursive.py +10 -0
  120. thebleep/rules/grunt_task_not_found.py +40 -0
  121. thebleep/rules/gulp_not_task.py +22 -0
  122. thebleep/rules/has_exists_script.py +13 -0
  123. thebleep/rules/heroku_multiple_apps.py +13 -0
  124. thebleep/rules/heroku_not_command.py +11 -0
  125. thebleep/rules/history.py +15 -0
  126. thebleep/rules/hostscli.py +27 -0
  127. thebleep/rules/ifconfig_device_not_found.py +23 -0
  128. thebleep/rules/java.py +17 -0
  129. thebleep/rules/javac.py +18 -0
  130. thebleep/rules/lein_not_task.py +19 -0
  131. thebleep/rules/ln_no_hard_link.py +23 -0
  132. thebleep/rules/ln_s_order.py +26 -0
  133. thebleep/rules/long_form_help.py +27 -0
  134. thebleep/rules/ls_all.py +10 -0
  135. thebleep/rules/ls_lah.py +12 -0
  136. thebleep/rules/man.py +42 -0
  137. thebleep/rules/man_no_space.py +10 -0
  138. thebleep/rules/mercurial.py +27 -0
  139. thebleep/rules/missing_space_before_subcommand.py +36 -0
  140. thebleep/rules/mkdir_p.py +29 -0
  141. thebleep/rules/mvn_no_command.py +11 -0
  142. thebleep/rules/mvn_unknown_lifecycle_phase.py +30 -0
  143. thebleep/rules/nixos_cmd_not_found.py +16 -0
  144. thebleep/rules/no_command.py +41 -0
  145. thebleep/rules/no_such_file.py +30 -0
  146. thebleep/rules/npm_missing_script.py +22 -0
  147. thebleep/rules/npm_run_script.py +17 -0
  148. thebleep/rules/npm_wrong_command.py +74 -0
  149. thebleep/rules/omnienv_no_such_command.py +38 -0
  150. thebleep/rules/open.py +40 -0
  151. thebleep/rules/pacman.py +17 -0
  152. thebleep/rules/pacman_invalid_option.py +24 -0
  153. thebleep/rules/pacman_not_found.py +31 -0
  154. thebleep/rules/path_from_history.py +53 -0
  155. thebleep/rules/php_s.py +11 -0
  156. thebleep/rules/ping_url.py +99 -0
  157. thebleep/rules/pip_externally_managed.py +105 -0
  158. thebleep/rules/pip_install.py +24 -0
  159. thebleep/rules/pip_unknown_command.py +19 -0
  160. thebleep/rules/port_already_in_use.py +44 -0
  161. thebleep/rules/prove_recursively.py +27 -0
  162. thebleep/rules/python_command.py +17 -0
  163. thebleep/rules/python_execute.py +15 -0
  164. thebleep/rules/python_module_error.py +54 -0
  165. thebleep/rules/quotation_marks.py +37 -0
  166. thebleep/rules/rails_migrations_pending.py +14 -0
  167. thebleep/rules/react_native_command_unrecognized.py +34 -0
  168. thebleep/rules/remove_shell_prompt_literal.py +23 -0
  169. thebleep/rules/remove_trailing_cedilla.py +11 -0
  170. thebleep/rules/rm_dir.py +34 -0
  171. thebleep/rules/rm_root.py +16 -0
  172. thebleep/rules/scm_correction.py +35 -0
  173. thebleep/rules/sed_unterminated_s.py +18 -0
  174. thebleep/rules/sl_ls.py +14 -0
  175. thebleep/rules/ssh_known_hosts.py +77 -0
  176. thebleep/rules/sudo.py +74 -0
  177. thebleep/rules/sudo_command_from_user_path.py +23 -0
  178. thebleep/rules/switch_lang.py +117 -0
  179. thebleep/rules/systemctl.py +22 -0
  180. thebleep/rules/terraform_init.py +22 -0
  181. thebleep/rules/terraform_no_command.py +16 -0
  182. thebleep/rules/test.py.py +10 -0
  183. thebleep/rules/tmux.py +18 -0
  184. thebleep/rules/touch.py +22 -0
  185. thebleep/rules/tsuru_login.py +12 -0
  186. thebleep/rules/tsuru_not_command.py +15 -0
  187. thebleep/rules/unknown_command.py +19 -0
  188. thebleep/rules/unsudo.py +13 -0
  189. thebleep/rules/vagrant_up.py +22 -0
  190. thebleep/rules/whois.py +43 -0
  191. thebleep/rules/workon_doesnt_exists.py +32 -0
  192. thebleep/rules/wrong_hyphen_before_subcommand.py +20 -0
  193. thebleep/rules/yarn_alias.py +14 -0
  194. thebleep/rules/yarn_command_not_found.py +43 -0
  195. thebleep/rules/yarn_command_replaced.py +13 -0
  196. thebleep/rules/yarn_help.py +17 -0
  197. thebleep/rules/yum_invalid_operation.py +39 -0
  198. thebleep/shells/__init__.py +85 -0
  199. thebleep/shells/bash.py +164 -0
  200. thebleep/shells/fish.py +176 -0
  201. thebleep/shells/generic.py +315 -0
  202. thebleep/shells/nushell.py +408 -0
  203. thebleep/shells/powershell.py +157 -0
  204. thebleep/shells/tcsh.py +67 -0
  205. thebleep/shells/zsh.py +132 -0
  206. thebleep/specific/__init__.py +0 -0
  207. thebleep/specific/apt.py +3 -0
  208. thebleep/specific/archlinux.py +59 -0
  209. thebleep/specific/brew.py +21 -0
  210. thebleep/specific/dnf.py +3 -0
  211. thebleep/specific/git.py +31 -0
  212. thebleep/specific/nix.py +3 -0
  213. thebleep/specific/npm.py +21 -0
  214. thebleep/specific/sudo.py +17 -0
  215. thebleep/specific/yum.py +3 -0
  216. thebleep/system/__init__.py +7 -0
  217. thebleep/system/paths.py +63 -0
  218. thebleep/system/streams.py +28 -0
  219. thebleep/system/unix.py +95 -0
  220. thebleep/system/win32.py +84 -0
  221. thebleep/types.py +331 -0
  222. thebleep/ui.py +174 -0
  223. thebleep/utils.py +607 -0
  224. thebleep/wrappers.py +322 -0
  225. thebleep-4.0.0.dist-info/METADATA +1327 -0
  226. thebleep-4.0.0.dist-info/RECORD +230 -0
  227. thebleep-4.0.0.dist-info/WHEEL +5 -0
  228. thebleep-4.0.0.dist-info/entry_points.txt +3 -0
  229. thebleep-4.0.0.dist-info/licenses/LICENSE.md +23 -0
  230. thebleep-4.0.0.dist-info/top_level.txt +1 -0
thebleep/__init__.py ADDED
File without changes
thebleep/__main__.py ADDED
@@ -0,0 +1,16 @@
1
+ """`python -m thebleep`, which runs exactly what the `thebleep` command runs.
2
+
3
+ Worth having on its own -- it is how you reach a tool installed into an
4
+ environment whose `Scripts` or `bin` directory is not on `PATH` -- and it
5
+ matters most on Windows. There the installed `thebleep.exe` is a launcher stub
6
+ that starts a second process to do the work, and starting a process is the
7
+ dearest thing that platform does -- an interpreter takes several times longer to
8
+ start there than on Linux, and the stub pays it twice. This reaches the same
9
+ entry point without the stub.
10
+
11
+ """
12
+
13
+ from .entrypoints.main import main
14
+
15
+ if __name__ == '__main__':
16
+ main()
@@ -0,0 +1,203 @@
1
+ import sys
2
+ from .const import ARGUMENT_PLACEHOLDER, SHELLS, get_alias
3
+
4
+ # The defaults every parse starts from, and the flags the fast path below can
5
+ # account for on its own. Everything else means argparse gets the job.
6
+ DEFAULTS = {'alias': None,
7
+ 'alias_loader': None,
8
+ 'clear_cache': False,
9
+ 'command': [],
10
+ 'debug': False,
11
+ 'doctor': False,
12
+ 'edit': False,
13
+ 'explain': False,
14
+ 'enable_experimental_instant_mode': False,
15
+ 'force_command': None,
16
+ 'help': False,
17
+ 'repeat': False,
18
+ 'shell': None,
19
+ 'shell_logger': None,
20
+ 'version': False,
21
+ 'yes': False}
22
+
23
+ SIMPLE_FLAGS = {'-y': 'yes',
24
+ '--yes': 'yes',
25
+ '--yeah': 'yes',
26
+ '--hard': 'yes',
27
+ '-r': 'repeat',
28
+ '--repeat': 'repeat',
29
+ '-e': 'edit',
30
+ '--explain': 'explain',
31
+ '--edit': 'edit',
32
+ '-d': 'debug',
33
+ '--debug': 'debug'}
34
+
35
+
36
+ class Arguments(object):
37
+ """What argparse would have returned, without importing argparse."""
38
+
39
+ def __init__(self, **values):
40
+ self.__dict__.update(DEFAULTS)
41
+ self.__dict__.update(values)
42
+
43
+
44
+ def _fast_parse(arguments):
45
+ """Parses the shapes the alias actually produces, or returns None.
46
+
47
+ Correcting a command is the overwhelmingly common case and it only ever
48
+ involves a command and a couple of switches. argparse costs more to import
49
+ than the rest of a correction takes, so it is kept for the command lines
50
+ that need it: `--help`, `--version`, anything taking a value, anything
51
+ unrecognised, and anything contradictory.
52
+
53
+ """
54
+ values = {}
55
+ for index, argument in enumerate(arguments):
56
+ if argument == '--':
57
+ command = arguments[index + 1:]
58
+ if any(item == '--' for item in command):
59
+ return None
60
+ values['command'] = command
61
+ break
62
+ flag = SIMPLE_FLAGS.get(argument)
63
+ if flag is None:
64
+ return None
65
+ if flag == 'yes' and values.get('repeat'):
66
+ return None # `-y` with `-r` is an error argparse must report
67
+ if flag == 'repeat' and values.get('yes'):
68
+ return None
69
+ values[flag] = True
70
+
71
+ return Arguments(**values)
72
+
73
+
74
+ class Parser(object):
75
+ """Argument parser that can handle arguments with our special
76
+ placeholder.
77
+
78
+ """
79
+
80
+ def __init__(self):
81
+ self._parser = None
82
+
83
+ def _build(self):
84
+ """Builds the real parser, for the command lines that need one."""
85
+ if self._parser is not None:
86
+ return self._parser
87
+
88
+ from argparse import ArgumentParser
89
+
90
+ self._parser = ArgumentParser(prog='thebleep', add_help=False)
91
+ self._add_arguments()
92
+ return self._parser
93
+
94
+ def _add_arguments(self):
95
+ """Adds arguments to parser."""
96
+ self._parser.add_argument(
97
+ '-v', '--version',
98
+ action='store_true',
99
+ help="show program's version number and exit")
100
+ self._parser.add_argument(
101
+ '-a', '--alias',
102
+ nargs='?',
103
+ const=get_alias(),
104
+ help='[custom-alias-name] prints alias for current shell')
105
+ self._parser.add_argument(
106
+ '--alias-loader',
107
+ nargs='?',
108
+ const=get_alias(),
109
+ help='[custom-alias-name] prints shell code that defines the alias'
110
+ ' on first use, so shell startup costs nothing')
111
+ self._parser.add_argument(
112
+ '--shell',
113
+ action='store',
114
+ metavar='SHELL',
115
+ help='the shell to act as, when working it out from the process'
116
+ ' tree gets it wrong: {}'.format(', '.join(sorted(SHELLS))))
117
+ self._parser.add_argument(
118
+ '--doctor',
119
+ action='store_true',
120
+ help='report what is installed and configured, and what is wrong')
121
+ self._parser.add_argument(
122
+ '--clear-cache',
123
+ action='store_true',
124
+ help='forget the compiled rules and the cached command lookups')
125
+ self._parser.add_argument(
126
+ '-l', '--shell-logger',
127
+ action='store',
128
+ help='log shell output to the file')
129
+ self._parser.add_argument(
130
+ '--enable-experimental-instant-mode',
131
+ action='store_true',
132
+ help='enable experimental instant mode, use on your own risk')
133
+ self._parser.add_argument(
134
+ '-h', '--help',
135
+ action='store_true',
136
+ help='show this help message and exit')
137
+ self._parser.add_argument(
138
+ '-e', '--edit',
139
+ action='store_true',
140
+ help='put the correction in your command line to edit'
141
+ ' instead of running it')
142
+ self._parser.add_argument(
143
+ '--explain',
144
+ action='store_true',
145
+ help='say which rule made each suggestion and what it matched')
146
+ self._add_conflicting_arguments()
147
+ self._parser.add_argument(
148
+ '-d', '--debug',
149
+ action='store_true',
150
+ help='enable debug output')
151
+ from argparse import SUPPRESS
152
+
153
+ self._parser.add_argument(
154
+ '--force-command',
155
+ action='store',
156
+ help=SUPPRESS)
157
+ self._parser.add_argument(
158
+ 'command',
159
+ nargs='*',
160
+ help='command that should be fixed')
161
+
162
+ def _add_conflicting_arguments(self):
163
+ """It's too dangerous to use `-y` and `-r` together."""
164
+ group = self._parser.add_mutually_exclusive_group()
165
+ group.add_argument(
166
+ '-y', '--yes', '--yeah', '--hard',
167
+ action='store_true',
168
+ help='execute fixed command without confirmation')
169
+ group.add_argument(
170
+ '-r', '--repeat',
171
+ action='store_true',
172
+ help='repeat on failure')
173
+
174
+ def _prepare_arguments(self, argv):
175
+ """Prepares arguments by:
176
+
177
+ - removing placeholder and moving arguments after it to beginning,
178
+ we need this to distinguish arguments from `command` with ours;
179
+
180
+ - adding `--` before `command`, so our parse would ignore arguments
181
+ of `command`.
182
+
183
+ """
184
+ if ARGUMENT_PLACEHOLDER in argv:
185
+ index = argv.index(ARGUMENT_PLACEHOLDER)
186
+ return argv[index + 1:] + ['--'] + argv[:index]
187
+ elif argv and not argv[0].startswith('-') and argv[0] != '--':
188
+ return ['--'] + argv
189
+ else:
190
+ return argv
191
+
192
+ def parse(self, argv):
193
+ arguments = self._prepare_arguments(argv[1:])
194
+ fast = _fast_parse(arguments)
195
+ if fast is not None:
196
+ return fast
197
+ return self._build().parse_args(arguments)
198
+
199
+ def print_usage(self):
200
+ self._build().print_usage(sys.stderr)
201
+
202
+ def print_help(self):
203
+ self._build().print_help(sys.stderr)
thebleep/cachefile.py ADDED
@@ -0,0 +1,89 @@
1
+ """A small on-disk cache for answers that are expensive to work out again.
2
+
3
+ `shelve` was doing this job, and it costs `dbm` and `pickle` at import time
4
+ before it has stored anything. What the app actually caches is plain data —
5
+ lists of names, a few booleans — so this stores it with `marshal` in one file
6
+ per subject and skips both.
7
+
8
+ Like the rule pack, this is only ever an optimisation: an unreadable or stale
9
+ cache costs time, never correctness.
10
+ """
11
+
12
+ import marshal
13
+ import os
14
+ import time
15
+ from .system import expanduser, writable
16
+
17
+ FORMAT = 3
18
+
19
+
20
+ def directory():
21
+ """Where The Bleep keeps everything it caches."""
22
+ cache_home = os.environ.get('XDG_CACHE_HOME') or '~/.cache'
23
+ return writable(expanduser(cache_home).joinpath('thebleep'), 'cache')
24
+
25
+
26
+ def path_for(name):
27
+ return directory().joinpath('{}.cache'.format(name))
28
+
29
+
30
+ def load(name, fingerprint, max_age=None):
31
+ """The cached value stored under `name`, if it was stored for this input.
32
+
33
+ The fingerprint is whatever makes the answer valid — a set of paths and
34
+ their modification times, a version, a setting. A different one is a miss.
35
+
36
+ `max_age`, in seconds, bounds how wrong a fingerprint is allowed to be.
37
+ Directory timestamps come from a coarse clock, so a change made in the same
38
+ clock tick as the last read would otherwise go unnoticed indefinitely.
39
+
40
+ """
41
+ try:
42
+ with path_for(name).open('rb') as handle:
43
+ cached = marshal.load(handle)
44
+ except Exception:
45
+ return None
46
+ if not isinstance(cached, dict) or cached.get('format') != FORMAT:
47
+ return None
48
+ if cached.get('fingerprint') != fingerprint:
49
+ return None
50
+ if max_age is not None:
51
+ saved_at = cached.get('saved_at')
52
+ if not saved_at or time.time() - saved_at > max_age:
53
+ return None
54
+ return cached.get('value')
55
+
56
+
57
+ def save(name, fingerprint, value):
58
+ """Stores a value, or quietly gives up when the cache isn't writable."""
59
+ path = path_for(name)
60
+ temp = None
61
+ try:
62
+ path.parent.mkdir(parents=True, exist_ok=True)
63
+ temp = path.parent.joinpath('{}.{}.tmp'.format(path.name, os.getpid()))
64
+ with temp.open('wb') as handle:
65
+ marshal.dump({'format': FORMAT, 'fingerprint': fingerprint,
66
+ 'saved_at': time.time(), 'value': value}, handle)
67
+ os.replace(str(temp), str(path))
68
+ except Exception:
69
+ if temp is not None:
70
+ try:
71
+ os.unlink(str(temp))
72
+ except OSError:
73
+ pass
74
+ return value
75
+
76
+
77
+ def clear():
78
+ """Removes every cache file. Returns how many were removed."""
79
+ removed = 0
80
+ try:
81
+ for entry in directory().glob('*.cache'):
82
+ try:
83
+ os.unlink(str(entry))
84
+ removed += 1
85
+ except OSError:
86
+ pass
87
+ except Exception:
88
+ pass
89
+ return removed
thebleep/conf.py ADDED
@@ -0,0 +1,232 @@
1
+ import os
2
+ import sys
3
+ from warnings import warn
4
+ from . import const
5
+ from .system import Path, expanduser, writable
6
+
7
+
8
+ def load_source(name, pathname, _file=None):
9
+ # Only a rule that is not in the pack, or a user's own settings file, gets
10
+ # here. Importing the machinery to load one costs every correction that
11
+ # never needs it.
12
+ import importlib.util
13
+
14
+ module_spec = importlib.util.spec_from_file_location(name, pathname)
15
+ module = importlib.util.module_from_spec(module_spec)
16
+ module_spec.loader.exec_module(module)
17
+ return module
18
+
19
+
20
+ class Settings(dict):
21
+ def __getattr__(self, item):
22
+ return self.get(item)
23
+
24
+ def __setattr__(self, key, value):
25
+ self[key] = value
26
+
27
+ def init(self, args=None):
28
+ """Fills `settings` with values from `settings.py` and env."""
29
+ from .logs import exception
30
+
31
+ self._setup_user_dir()
32
+ self._init_settings_file()
33
+
34
+ try:
35
+ self.update(self._settings_from_file())
36
+ except Exception:
37
+ exception("Can't load settings from file", sys.exc_info())
38
+
39
+ try:
40
+ self.update(self._settings_from_env())
41
+ except Exception:
42
+ exception("Can't load settings from env", sys.exc_info())
43
+
44
+ self.update(self._settings_from_args(args))
45
+
46
+ def _init_settings_file(self):
47
+ settings_path = self.user_dir.joinpath('settings.py')
48
+ if not settings_path.is_file():
49
+ with settings_path.open(mode='w') as settings_file:
50
+ settings_file.write(const.SETTINGS_HEADER)
51
+ for setting in const.DEFAULT_SETTINGS.items():
52
+ settings_file.write(u'# {} = {}\n'.format(*setting))
53
+
54
+ def _get_user_dir_path(self):
55
+ """Returns Path object representing the user config resource"""
56
+ xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '~/.config')
57
+ # `writable`, because this is somewhere we create and write to: with no
58
+ # home directory to expand `~` against, the alternative is a directory
59
+ # named `~` in whatever the working directory happens to be.
60
+ user_dir = writable(expanduser(Path(xdg_config_home, 'thebleep')),
61
+ 'config')
62
+ legacy_user_dir = expanduser(Path('~', '.thebleep'))
63
+
64
+ # For backward compatibility use legacy '~/.thebleep' if it exists:
65
+ if legacy_user_dir.is_dir():
66
+ warn(u'Config path {} is deprecated. Please move to {}'.format(
67
+ legacy_user_dir, user_dir))
68
+ return legacy_user_dir
69
+ else:
70
+ return user_dir
71
+
72
+ def _setup_user_dir(self):
73
+ """Returns user config dir, create it when it doesn't exist."""
74
+ user_dir = self._get_user_dir_path()
75
+
76
+ rules_dir = user_dir.joinpath('rules')
77
+ if not rules_dir.is_dir():
78
+ rules_dir.mkdir(parents=True)
79
+ self.user_dir = user_dir
80
+
81
+ def _settings_from_file(self):
82
+ """Loads settings from file.
83
+
84
+ Run rather than imported. `load_source` builds a real module through
85
+ `importlib.util`, and a settings file is a handful of assignments whose
86
+ names are all this reads back -- so the module was machinery nobody
87
+ used, and `importlib.util` (with `contextlib` behind it) was imported on
88
+ every correction to get it. A settings file that imports something of
89
+ its own still works: this is the same compile and the same execution,
90
+ into a namespace instead of a module.
91
+
92
+ """
93
+ path = str(self.user_dir.joinpath('settings.py'))
94
+ with open(path, 'rb') as handle:
95
+ source = handle.read()
96
+
97
+ namespace = {'__file__': path, '__name__': 'settings'}
98
+ exec(compile(source, path, 'exec'), namespace)
99
+ from_file = {key: namespace[key]
100
+ for key in const.DEFAULT_SETTINGS.keys()
101
+ if key in namespace}
102
+ for key in ('rules', 'exclude_rules'):
103
+ if key in from_file:
104
+ from_file[key] = self._expand_default_rules(from_file[key])
105
+ return from_file
106
+
107
+ def _expand_default_rules(self, rules):
108
+ """A rules list with the `DEFAULT_RULES` sentinel expanded.
109
+
110
+ The environment variable spells "and everything that is on by default"
111
+ as the string `DEFAULT_RULES`, and every example spells it that way. In
112
+ a settings file the same string used to mean a rule of that name, of
113
+ which there is none -- so `rules = ['DEFAULT_RULES', 'python_module_error']`
114
+ enabled one rule and disabled the other 172, and the only symptom was
115
+ that nothing was ever corrected again. It means the same thing in both
116
+ places now.
117
+
118
+ A settings file is Python, so `from thebleep.const import DEFAULT_RULES`
119
+ and splicing the real constant in works as well, and always did.
120
+
121
+ """
122
+ if not isinstance(rules, list) or 'DEFAULT_RULES' not in rules:
123
+ return rules
124
+ return [item for rule in rules
125
+ for item in (const.DEFAULT_RULES if rule == 'DEFAULT_RULES'
126
+ else [rule])]
127
+
128
+ def _rules_from_env(self, val):
129
+ """Transforms rules list from env-string to python."""
130
+ return self._expand_default_rules(val.split(':'))
131
+
132
+ def _priority_from_env(self, val):
133
+ """Gets priority pairs from env."""
134
+ for part in val.split(':'):
135
+ try:
136
+ rule, priority = part.split('=')
137
+ yield rule, int(priority)
138
+ except ValueError:
139
+ continue
140
+
141
+ # What counts as yes and what counts as no. It used to be `== 'true'` and
142
+ # anything else at all, so `THEBLEEP_DEBUG=1` quietly meant no.
143
+ BOOLEANS = {'true': True, 'yes': True, 'on': True, '1': True,
144
+ 'false': False, 'no': False, 'off': False, '0': False}
145
+
146
+ # A timeout of zero means never waiting; a history limit or a number of
147
+ # suggestions of zero means the setting does nothing, which nobody sets on
148
+ # purpose and which reads as the feature being broken.
149
+ COUNTS = {'wait_command': 0, 'wait_slow_command': 0,
150
+ 'history_limit': 1, 'num_close_matches': 1}
151
+
152
+ def _number_from_env(self, attr, val):
153
+ try:
154
+ number = int(val)
155
+ except ValueError:
156
+ raise ValueError('{!r} is not a number'.format(val))
157
+ least = self.COUNTS[attr]
158
+ if number < least:
159
+ raise ValueError('{} is less than {}'.format(number, least))
160
+ return number
161
+
162
+ def _bool_from_env(self, val):
163
+ try:
164
+ return self.BOOLEANS[val.strip().lower()]
165
+ except KeyError:
166
+ raise ValueError(
167
+ '{!r} is neither true nor false'.format(val))
168
+
169
+ def _val_from_env(self, env, attr):
170
+ """Transforms env-strings to python."""
171
+ val = os.environ[env]
172
+ if attr in ('rules', 'exclude_rules'):
173
+ return self._rules_from_env(val)
174
+ elif attr == 'priority':
175
+ return dict(self._priority_from_env(val))
176
+ elif attr in self.COUNTS:
177
+ return self._number_from_env(attr, val)
178
+ elif attr in ('require_confirmation', 'no_colors', 'debug',
179
+ 'alter_history', 'instant_mode', 'confirm_replay',
180
+ 'edit', 'explain'):
181
+ return self._bool_from_env(val)
182
+ elif attr in ('slow_commands', 'excluded_search_path_prefixes'):
183
+ return val.split(':')
184
+ else:
185
+ return val
186
+
187
+ def _settings_from_env(self):
188
+ """Loads settings from env, one variable at a time.
189
+
190
+ One at a time on purpose. This was a comprehension, so one value that
191
+ would not parse -- `THEBLEEP_WAIT_COMMAND=abc` -- raised out of the whole
192
+ thing, the caller's `update` never happened, and *every* environment
193
+ setting was silently dropped: colours came back on, excluded rules came
194
+ back with them. A setting that cannot be understood now costs that
195
+ setting, says so, and costs nothing else.
196
+
197
+ """
198
+ from .logs import warn
199
+
200
+ settings = {}
201
+ for env, attr in sorted(const.ENV_TO_ATTR.items()):
202
+ if env not in os.environ:
203
+ continue
204
+ try:
205
+ settings[attr] = self._val_from_env(env, attr)
206
+ except ValueError as error:
207
+ warn(u'Ignoring {}: {}.'.format(env, error))
208
+ return settings
209
+
210
+ def _settings_from_args(self, args):
211
+ """Loads settings from args."""
212
+ if not args:
213
+ return {}
214
+
215
+ from_args = {}
216
+ if args.yes:
217
+ from_args['require_confirmation'] = not args.yes
218
+ # `--yes` is consent given for this run, so it covers running the
219
+ # previous command again as well as the correction.
220
+ from_args['confirm_replay'] = False
221
+ if args.debug:
222
+ from_args['debug'] = args.debug
223
+ if args.repeat:
224
+ from_args['repeat'] = args.repeat
225
+ if args.edit:
226
+ from_args['edit'] = args.edit
227
+ if args.explain:
228
+ from_args['explain'] = args.explain
229
+ return from_args
230
+
231
+
232
+ settings = Settings(const.DEFAULT_SETTINGS)