deadcode 2.3.2__py3-none-any.whl → 2.4.1__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.
deadcode/__init__.py CHANGED
@@ -0,0 +1,8 @@
1
+ try:
2
+ import importlib.metadata
3
+
4
+ __version__ = importlib.metadata.version(__package__ or __name__)
5
+ except ImportError:
6
+ import importlib_metadata
7
+
8
+ __version__ = importlib_metadata.version(__package__ or __name__)
@@ -38,27 +38,28 @@ def fix_or_show_unused_code(unused_items: Iterable[CodeItem], args: Args) -> str
38
38
  updated_file_content_lines = remove_file_parts_from_content(file_content_lines, unused_file_parts)
39
39
  updated_file_content = b''.join(updated_file_content_lines)
40
40
  if updated_file_content.strip():
41
- if args.dry and ('__all_files__' in args.dry or _match(filename, args.dry)):
42
- with open(filename, 'rb') as f:
43
- filename_bytes = filename.encode()
44
- diff = diff_bytes(
45
- unified_diff,
46
- f.readlines(),
47
- updated_file_content_lines,
48
- fromfile=filename_bytes,
49
- tofile=filename_bytes,
50
- )
51
- # TODO: consider printing result instantly to save memory
52
- result_chunk = b''.join(diff)
53
- if args.no_color:
54
- result.append(result_chunk)
55
- else:
56
- result.append(add_colors_to_diff(result_chunk))
41
+ if not args.only or _match(filename, args.only):
42
+ if args.dry:
43
+ with open(filename, 'rb') as f:
44
+ filename_bytes = filename.encode()
45
+ diff = diff_bytes(
46
+ unified_diff,
47
+ f.readlines(),
48
+ updated_file_content_lines,
49
+ fromfile=filename_bytes,
50
+ tofile=filename_bytes,
51
+ )
52
+ # TODO: consider printing result instantly to save memory
53
+ result_chunk = b''.join(diff)
54
+ if args.no_color:
55
+ result.append(result_chunk)
56
+ else:
57
+ result.append(add_colors_to_diff(result_chunk))
57
58
 
58
- elif args.fix:
59
- with open(filename, 'wb') as f:
60
- # TODO: is there a method writelines?
61
- f.write(updated_file_content)
59
+ elif args.fix:
60
+ with open(filename, 'wb') as f:
61
+ # TODO: is there a method writelines?
62
+ f.write(updated_file_content)
62
63
  else:
63
64
  os.remove(filename)
64
65
 
@@ -2,6 +2,7 @@ from typing import Iterable, Optional
2
2
 
3
3
  from deadcode.data_types import Args
4
4
  from deadcode.visitor.code_item import CodeItem
5
+ from deadcode.visitor.ignore import _match
5
6
 
6
7
 
7
8
  def get_unused_names_error_message(unused_names: Iterable[CodeItem], args: Args) -> Optional[str]:
@@ -18,16 +19,17 @@ def get_unused_names_error_message(unused_names: Iterable[CodeItem], args: Args)
18
19
 
19
20
  messages = []
20
21
  for item in unused_names:
21
- message = f'{item.filename_with_position} \033[91m{item.error_code}\033[0m '
22
- message += item.message or (
23
- f"{item.type_.replace('_', ' ').capitalize()} " f"`\033[1m{item.name}\033[0m` " f"is never used"
24
- )
25
- if args.no_color:
26
- message = message.replace('\033[91m', '').replace('\033[1m', '').replace('\033[0m', '')
27
- messages.append(message)
22
+ if not args.only or _match(item.filename, args.only):
23
+ message = f'{item.filename_with_position} \033[91m{item.error_code}\033[0m '
24
+ message += item.message or (
25
+ f"{item.type_.replace('_', ' ').capitalize()} " f"`\033[1m{item.name}\033[0m` " f"is never used"
26
+ )
27
+ if args.no_color:
28
+ message = message.replace('\033[91m', '').replace('\033[1m', '').replace('\033[0m', '')
29
+ messages.append(message)
28
30
 
29
31
  if args.fix:
30
- message = f"\nRemoved \033[1m{len(unused_names)}\033[0m unused code item{'s' if len(unused_names) > 1 else ''}!"
32
+ message = f"\nRemoved \033[1m{len(messages)}\033[0m unused code item{'s' if len(messages) > 1 else ''}!"
31
33
  if args.no_color:
32
34
  message = message.replace('\x1b[1m', '').replace('\x1b[0m', '')
33
35
  messages.append(message)
@@ -36,9 +36,15 @@ def parse_arguments(args: Optional[List[str]]) -> Args:
36
36
  parser.add_argument(
37
37
  '--dry',
38
38
  help='Show changes which would be made in files with --fix option.',
39
+ action='store_true',
40
+ default=False,
41
+ )
42
+ parser.add_argument(
43
+ '--only',
44
+ help='Filenames (or path expressions), that will be reflected in the output and modified.',
39
45
  nargs='*',
40
46
  action='append',
41
- default=[['__all_files__']],
47
+ default=[],
42
48
  type=str,
43
49
  )
44
50
  parser.add_argument(
@@ -188,6 +194,12 @@ def parse_arguments(args: Optional[List[str]]) -> Args:
188
194
  action='store_true',
189
195
  default=False,
190
196
  )
197
+ parser.add_argument(
198
+ '--version',
199
+ help='Shows deadcode version',
200
+ action='store_true',
201
+ default=False,
202
+ )
191
203
 
192
204
  parsed_args = parser.parse_args(args).__dict__
193
205
 
@@ -200,10 +212,6 @@ def parse_arguments(args: Optional[List[str]]) -> Args:
200
212
  if key in parsed_args:
201
213
  parsed_args[key].extend(item)
202
214
 
203
- # Show changes for only provided files instead of all
204
- if len(parsed_args['dry']) > 1 or '--dry' not in args:
205
- parsed_args['dry'].remove('__all_files__')
206
-
207
215
  # Do not fix if dry option is provided:
208
216
  if parsed_args['dry']:
209
217
  parsed_args['fix'] = False
deadcode/cli.py CHANGED
@@ -1,5 +1,7 @@
1
1
  from typing import List, Optional
2
+ import sys
2
3
 
4
+ from deadcode import __version__
3
5
  from deadcode.actions.find_python_filenames import find_python_filenames
4
6
  from deadcode.actions.find_unused_names import find_unused_names
5
7
  from deadcode.actions.fix_or_show_unused_code import fix_or_show_unused_code
@@ -12,6 +14,10 @@ from deadcode.actions.get_unused_names_error_message import (
12
14
  def main(
13
15
  command_line_args: Optional[List[str]] = None,
14
16
  ) -> Optional[str]:
17
+
18
+ if command_line_args and '--version' in command_line_args or '--version' in sys.argv:
19
+ return __version__
20
+
15
21
  args = parse_arguments(command_line_args)
16
22
 
17
23
  filenames = find_python_filenames(args=args)
@@ -31,5 +37,10 @@ def main(
31
37
  return None
32
38
 
33
39
 
40
+ def print_main() -> None:
41
+ if result := main():
42
+ print(result)
43
+
44
+
34
45
  if __name__ == '__main__':
35
- main()
46
+ print_main()
deadcode/data_types.py CHANGED
@@ -14,7 +14,9 @@ Pathname = str # Can contain wildewards
14
14
  class Args:
15
15
  fix: bool = False
16
16
  verbose: bool = False
17
- dry: Iterable[Pathname] = ()
17
+ version: bool = False
18
+ dry: bool = False
19
+ only: Iterable[Pathname] = ()
18
20
  paths: Iterable[Pathname] = ()
19
21
  exclude: Iterable[Pathname] = ()
20
22
  ignore_definitions: Iterable[Pathname] = ()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: deadcode
3
- Version: 2.3.2
3
+ Version: 2.4.1
4
4
  Summary: Find and remove dead code.
5
5
  Project-URL: homepage, https://github.com/albertas/deadcode
6
6
  Project-URL: documentation, https://deadcode.readthedocs.io/
@@ -55,7 +55,7 @@ deadcode . --fix --dry
55
55
 
56
56
  To see suggested fixes only for `foo.py` file:
57
57
  ```shell
58
- deadcode . --fix --dry foo.py
58
+ deadcode . --fix --dry --only foo.py
59
59
  ```
60
60
 
61
61
  To fix:
@@ -81,7 +81,8 @@ ignore-names-in-files = ["migrations"]
81
81
  | Option                                    | Type | Meaning |
82
82
  |-------------------------------------------|------|----------------------------------------------------------------------|
83
83
  |`--fix` | - | Automatically remove detected unused code expressions from the code base. |
84
- |`--dry` | - or list | Show changes which would be made in files. Shows changes for provided filenames or shows all changes if no filename is specified. |
84
+ |`--dry` | - | Show changes which would be made in files. |
85
+ |`--only` | list | Filenames (or path expressions), that will be reflected in the output (and modified if needed). |
85
86
  |`--exclude` | list | Filenames (or path expressions), which will be completely skipped without being analysed. |
86
87
  |`--ignore-names` | list | Removes provided list of names from the output. Regexp expressions to match multiple names can also be provided, e.g. `*Mixin` will match all classes ending with `Mixin`. |
87
88
  |`--ignore-names-in-files` | list | Ignores unused names in files, which filenames match provided path expressions. |
@@ -184,13 +185,11 @@ code base is implemented in.
184
185
  - [ ] Distinguish between definitions with same name, but different files.
185
186
  - [ ] Repeated application of `deadcode` till the output stops changing.
186
187
  - [ ] Unreachable code detection and fixing: this should only be scoped for if statements and only limited to primitive variables.
187
- - [x] `--fix --dry [filenames]` - only show whats about to change in the listed filenames.
188
188
  - [ ] Benchmarking performance with larger projects (time, CPU and memory consumption) in order to optimize.
189
189
  - [ ] `--fix` could accept a list of filenames as well (only those files would be changed, but the summary could would be full).
190
190
  (This might be confusing, because filenames, which have to be considered are provided without any flag, --fix is expected to not accept arguments)
191
191
  - [ ] pre-commit-hook.
192
192
  - [ ] language server.
193
- - [x] Use only two digits for error codes instead of 3. Two is plenty and it simplifies usage a bit
194
193
  - [ ] DC10: remove code after terminal statements like `raise`, `return`, `break`, `continue` and comes in the same scope.
195
194
  - [ ] Add `ignore` and `per-file-ignores` command line and pyproject.toml options, which allows to skip some rules.
196
195
  - [ ] Make sure that all rules are being skipped by `noqa` comment and all rules react to `noqa: rule_id` comments.
@@ -199,11 +198,18 @@ code base is implemented in.
199
198
  documentation should cleary demonstrate the behaviour/example that "Schema" means "*.Schema".
200
199
  - [ ] Redefinition of an existing name makes previous name unreachable, unless it is assigned somehow.
201
200
  - [ ] Check if file is still valid/parsable after automatic fixing, if not: halt the change and report error.
201
+ - [ ] Investigate ways of extracting and backporting Python3.10+ `ast` implementation to lower Python versions.
202
202
 
203
203
  ## Release notes
204
+ - v2.4.1:
205
+ - Add `--version` option to show `deadcode` version.
206
+ - Use stdout for `deadcode` output.
207
+ - v2.4.0:
208
+ - Add `--only` option that accepts filenames only which will be reflected in the output and modified.
209
+ This option can be used with `--fix` and `--fix --dry` options as well as for simple unused code detection without fixing.
204
210
  - v2.3.2:
205
211
  - Add `pre-commit` hook support.
206
- - Drop support for Python 3.8 and 3.9 versions, since their ast implementation is lacking features.
212
+ - Drop support for Python 3.8 and 3.9 versions, since their `ast` implementation is lacking features.
207
213
  - v2.3.1:
208
214
  - Started analysing files in bytes instead of trying to convert them into UTF-8 encoded strings.
209
215
  - Improved automatic removal of unused imports.
@@ -1,15 +1,15 @@
1
- deadcode/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
- deadcode/cli.py,sha256=F9YO08LvhTAs_UIGklTvILR1Fw3ghDD0gafRy1-7xe8,1175
1
+ deadcode/__init__.py,sha256=-nvSi7hjcp572lXD-ercQdCJg2qJKYeBC7rLYPanSUs,227
2
+ deadcode/cli.py,sha256=yh-uAN8e16mf-BebfLtT9jWBr8kdYi8ZGUCYpNLdWHw,1419
3
3
  deadcode/constants.py,sha256=ya_JsIQGtWAgrEZWc2NpKtuhwkn_05tlGBQpAm3f3Hc,838
4
- deadcode/data_types.py,sha256=U7G0EZC0eioOoHoVhwq9nom2HKup5FDQaGrCOAMC89M,1314
4
+ deadcode/data_types.py,sha256=3BzU0LxTi00XtbIM8fh4RkdAoAeZsrbCyvyaSuNe5UA,1363
5
5
  deadcode/actions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
6
  deadcode/actions/find_python_filenames.py,sha256=uUKvCcisGc4zb6CjUDOhGYPjwW4S2Ysfr2MRhkMD7m0,1546
7
7
  deadcode/actions/find_unused_names.py,sha256=TagYxuxNrBarwmJ23tuxuCGNinj8mQo26RGZTh90a-8,494
8
- deadcode/actions/fix_or_show_unused_code.py,sha256=QtS7H618TjANuTs9tpQJF3b4I6aqvhZ_38yJn1Ley-o,2853
9
- deadcode/actions/get_unused_names_error_message.py,sha256=wYYZFSI7_TXPA3a_Qrn-8ttysezKDqErZEUqvWENI3E,1160
8
+ deadcode/actions/fix_or_show_unused_code.py,sha256=7txuOL_4wYiBecSMhGJ15YotNtlTWihzykQOPmTmc5M,2930
9
+ deadcode/actions/get_unused_names_error_message.py,sha256=OMQyCXYTs5FAEFzrcFHZAJ_UrrphbAfn9ahtQG7Nt1I,1285
10
10
  deadcode/actions/merge_overlaping_file_parts.py,sha256=ukErzpXCuUOWk5CCpPxD43edqoE087sGJGvYZnwUGXs,3165
11
11
  deadcode/actions/parse_abstract_syntax_tree.py,sha256=iL0ukt-FQKA9DuFUk7-sSJZ9nfBzDlJBY-ijItYR6PU,547
12
- deadcode/actions/parse_arguments.py,sha256=GbF4bqZDCzN1QV406jIj80zyVJ_Mbp8G3mundgxaHEc,6955
12
+ deadcode/actions/parse_arguments.py,sha256=gYbdHz_8bzWUXArLzeV0Mu1a4vnhSBKuGWsuluDJcSs,7113
13
13
  deadcode/actions/remove_file_parts_from_content.py,sha256=vz9fjniO6Tx3y-rUb4pmAWwU3BYbCBE4-ZY7aDNNnMI,6475
14
14
  deadcode/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
15
  deadcode/utils/add_colors_to_diff.py,sha256=JSEtaHbyojIpCOBa2UNCaKDJr0a9hxkeDlRB4h-YpBI,423
@@ -25,8 +25,8 @@ deadcode/visitor/ignore.py,sha256=m8qB8uKYB65D-53JOB5LKz32TF9c1y623EyZ1uFFc9A,31
25
25
  deadcode/visitor/lines.py,sha256=0NCrWAqYua7k93VYy7yLby7olhT2Pe4VU_Z5ImNKkjE,3241
26
26
  deadcode/visitor/noqa.py,sha256=0zRA9q0MzEzKe-N285JafP1DSJ3QqGL4GTb9m0QwCiY,2088
27
27
  deadcode/visitor/utils.py,sha256=55WcdKJPRrQiFrc0tIkcGO7dUkTnfvZ3qSzsLsTR4MI,2765
28
- deadcode-2.3.2.dist-info/METADATA,sha256=ZSyj3T_sYQJVBwOVKQZdQy0v2U2YVxEF9xUp4x16hL8,11658
29
- deadcode-2.3.2.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
30
- deadcode-2.3.2.dist-info/entry_points.txt,sha256=B0nEkycvQHBUJVGS4KmWCBtcWoEM87Gae6zHbrXCU2Q,47
31
- deadcode-2.3.2.dist-info/licenses/LICENSE,sha256=hIahDEOTzuHCU5J2nd07LWwkLW7Hko4UFO__ffsvB-8,34523
32
- deadcode-2.3.2.dist-info/RECORD,,
28
+ deadcode-2.4.1.dist-info/METADATA,sha256=CBnXRajVuYC5JBURud_5lruOBh9UJF9hODRYKijHimk,11999
29
+ deadcode-2.4.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
30
+ deadcode-2.4.1.dist-info/entry_points.txt,sha256=efJLd6DwsjycmpPFhvnql1ziW6xGx6VtAvZXNlREQxg,53
31
+ deadcode-2.4.1.dist-info/licenses/LICENSE,sha256=hIahDEOTzuHCU5J2nd07LWwkLW7Hko4UFO__ffsvB-8,34523
32
+ deadcode-2.4.1.dist-info/RECORD,,
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ deadcode = deadcode.cli:print_main
@@ -1,2 +0,0 @@
1
- [console_scripts]
2
- deadcode = deadcode.cli:main