dissolve 0.0.2__tar.gz → 0.1.0__tar.gz

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.
@@ -0,0 +1,165 @@
1
+ Metadata-Version: 2.1
2
+ Name: dissolve
3
+ Version: 0.1.0
4
+ Summary: Automatically replace use of deprecated APIs
5
+ Author-email: Jelmer Vernooij <jelmer@jelmer.uk>
6
+ License: Apachev2 or later
7
+ Project-URL: Homepage, https://github.com/jelmer/dissolve/
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: Implementation :: CPython
16
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
17
+ Classifier: Operating System :: POSIX
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/x-rst
20
+ License-File: COPYING
21
+ Requires-Dist: packaging
22
+ Provides-Extra: testing
23
+ Requires-Dist: pytest; extra == "testing"
24
+ Provides-Extra: dev
25
+ Requires-Dist: ruff==0.11.11; extra == "dev"
26
+ Requires-Dist: mypy==1.15.0; extra == "dev"
27
+
28
+ dissolve
29
+ ========
30
+
31
+ The dissolve library helps users replaces calls to deprecated library APIs.
32
+
33
+ Example
34
+ =======
35
+
36
+ E.g. if you had a function "inc" that has been renamed to "increment" in
37
+ version 0.1.0 of your library:
38
+
39
+ .. code-block:: python
40
+
41
+ from dissolve import replace_me
42
+
43
+ def increment(x):
44
+ return x + 1
45
+
46
+ @replace_me(since="0.1.0")
47
+ def inc(x):
48
+ return increment(x)
49
+
50
+
51
+ Running this code will yield a warning:
52
+
53
+ .. code-block:: console
54
+
55
+ ...
56
+ >>> inc(x=3)
57
+ <stdin>:1: DeprecationWarning: <function inc at 0x7feaf5ead5a0> has been deprecated since 0.1.0; use 'increment(x)' instead
58
+ 4
59
+
60
+
61
+ dissolve migrate
62
+ ================
63
+
64
+ The ``dissolve migrate`` command can automatically update your codebase to
65
+ replace deprecated function calls with their suggested replacements.
66
+
67
+ Usage:
68
+
69
+ .. code-block:: console
70
+
71
+ $ dissolve migrate path/to/code
72
+
73
+ This will:
74
+
75
+ 1. Search for Python files in the specified path
76
+ 2. Find calls to functions decorated with ``@replace_me``
77
+ 3. Replace them with the suggested replacement expression
78
+ 4. Show a diff of the changes
79
+
80
+ Options:
81
+
82
+ * ``-w, --write``: Write changes back to files instead of printing to stdout
83
+ * ``--check``: Check if files need migration without modifying them (exits with code 1 if changes are needed)
84
+
85
+ Examples:
86
+
87
+ Preview changes:
88
+
89
+ .. code-block:: console
90
+
91
+ $ dissolve migrate myproject/utils.py
92
+ # Migrated: myproject/utils.py
93
+ ...
94
+ result = 5 + 1
95
+ ...
96
+
97
+ Check if migration is needed:
98
+
99
+ .. code-block:: console
100
+
101
+ $ dissolve migrate --check myproject/
102
+ myproject/utils.py: needs migration
103
+ myproject/core.py: up to date
104
+ $ echo $?
105
+ 1
106
+
107
+ Apply changes:
108
+
109
+ .. code-block:: console
110
+
111
+ $ dissolve migrate --write myproject/
112
+ Modified: myproject/utils.py
113
+ Unchanged: myproject/core.py
114
+
115
+ The command respects the replacement expressions defined in the ``@replace_me``
116
+ decorator and substitutes actual argument values.
117
+
118
+
119
+ dissolve remove
120
+ ===============
121
+
122
+ The ``dissolve remove`` command can remove ``@replace_me`` decorators from your
123
+ codebase. This is useful when you want to clean up old deprecation markers.
124
+
125
+ Usage:
126
+
127
+ .. code-block:: console
128
+
129
+ $ dissolve remove [options] path/to/code
130
+
131
+ Options:
132
+
133
+ * ``--all``: Remove all ``@replace_me`` decorators regardless of version
134
+ * ``--before VERSION``: Remove only decorators with a version older than the specified version
135
+ * ``-w, --write``: Write changes back to files (default: print to stdout)
136
+ * ``--check``: Check if files have removable decorators without modifying them (exits with code 1 if changes are needed)
137
+
138
+ Examples:
139
+
140
+ Check if decorators can be removed:
141
+
142
+ .. code-block:: console
143
+
144
+ $ dissolve remove --check --all myproject/
145
+ myproject/utils.py: has removable decorators
146
+ myproject/core.py: no removable decorators
147
+ $ echo $?
148
+ 1
149
+
150
+ Remove all decorators:
151
+
152
+ .. code-block:: console
153
+
154
+ $ dissolve remove --all --write myproject/
155
+ Modified: myproject/utils.py
156
+ Unchanged: myproject/core.py
157
+
158
+ Remove decorators before version 2.0.0:
159
+
160
+ .. code-block:: console
161
+
162
+ $ dissolve remove --before 2.0.0 --write myproject/
163
+
164
+ This will remove decorators like ``@replace_me(since="1.0.0")`` but keep
165
+ ``@replace_me(since="2.0.0")`` and newer.
@@ -0,0 +1,138 @@
1
+ dissolve
2
+ ========
3
+
4
+ The dissolve library helps users replaces calls to deprecated library APIs.
5
+
6
+ Example
7
+ =======
8
+
9
+ E.g. if you had a function "inc" that has been renamed to "increment" in
10
+ version 0.1.0 of your library:
11
+
12
+ .. code-block:: python
13
+
14
+ from dissolve import replace_me
15
+
16
+ def increment(x):
17
+ return x + 1
18
+
19
+ @replace_me(since="0.1.0")
20
+ def inc(x):
21
+ return increment(x)
22
+
23
+
24
+ Running this code will yield a warning:
25
+
26
+ .. code-block:: console
27
+
28
+ ...
29
+ >>> inc(x=3)
30
+ <stdin>:1: DeprecationWarning: <function inc at 0x7feaf5ead5a0> has been deprecated since 0.1.0; use 'increment(x)' instead
31
+ 4
32
+
33
+
34
+ dissolve migrate
35
+ ================
36
+
37
+ The ``dissolve migrate`` command can automatically update your codebase to
38
+ replace deprecated function calls with their suggested replacements.
39
+
40
+ Usage:
41
+
42
+ .. code-block:: console
43
+
44
+ $ dissolve migrate path/to/code
45
+
46
+ This will:
47
+
48
+ 1. Search for Python files in the specified path
49
+ 2. Find calls to functions decorated with ``@replace_me``
50
+ 3. Replace them with the suggested replacement expression
51
+ 4. Show a diff of the changes
52
+
53
+ Options:
54
+
55
+ * ``-w, --write``: Write changes back to files instead of printing to stdout
56
+ * ``--check``: Check if files need migration without modifying them (exits with code 1 if changes are needed)
57
+
58
+ Examples:
59
+
60
+ Preview changes:
61
+
62
+ .. code-block:: console
63
+
64
+ $ dissolve migrate myproject/utils.py
65
+ # Migrated: myproject/utils.py
66
+ ...
67
+ result = 5 + 1
68
+ ...
69
+
70
+ Check if migration is needed:
71
+
72
+ .. code-block:: console
73
+
74
+ $ dissolve migrate --check myproject/
75
+ myproject/utils.py: needs migration
76
+ myproject/core.py: up to date
77
+ $ echo $?
78
+ 1
79
+
80
+ Apply changes:
81
+
82
+ .. code-block:: console
83
+
84
+ $ dissolve migrate --write myproject/
85
+ Modified: myproject/utils.py
86
+ Unchanged: myproject/core.py
87
+
88
+ The command respects the replacement expressions defined in the ``@replace_me``
89
+ decorator and substitutes actual argument values.
90
+
91
+
92
+ dissolve remove
93
+ ===============
94
+
95
+ The ``dissolve remove`` command can remove ``@replace_me`` decorators from your
96
+ codebase. This is useful when you want to clean up old deprecation markers.
97
+
98
+ Usage:
99
+
100
+ .. code-block:: console
101
+
102
+ $ dissolve remove [options] path/to/code
103
+
104
+ Options:
105
+
106
+ * ``--all``: Remove all ``@replace_me`` decorators regardless of version
107
+ * ``--before VERSION``: Remove only decorators with a version older than the specified version
108
+ * ``-w, --write``: Write changes back to files (default: print to stdout)
109
+ * ``--check``: Check if files have removable decorators without modifying them (exits with code 1 if changes are needed)
110
+
111
+ Examples:
112
+
113
+ Check if decorators can be removed:
114
+
115
+ .. code-block:: console
116
+
117
+ $ dissolve remove --check --all myproject/
118
+ myproject/utils.py: has removable decorators
119
+ myproject/core.py: no removable decorators
120
+ $ echo $?
121
+ 1
122
+
123
+ Remove all decorators:
124
+
125
+ .. code-block:: console
126
+
127
+ $ dissolve remove --all --write myproject/
128
+ Modified: myproject/utils.py
129
+ Unchanged: myproject/core.py
130
+
131
+ Remove decorators before version 2.0.0:
132
+
133
+ .. code-block:: console
134
+
135
+ $ dissolve remove --before 2.0.0 --write myproject/
136
+
137
+ This will remove decorators like ``@replace_me(since="1.0.0")`` but keep
138
+ ``@replace_me(since="2.0.0")`` and newer.
@@ -0,0 +1,54 @@
1
+ # Copyright (C) 2022 Jelmer Vernooij <jelmer@samba.org>
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Dissolve - A Python library for replacing deprecated API calls.
16
+
17
+ Dissolve helps library maintainers guide users from deprecated APIs to new ones
18
+ by providing clear, actionable replacement suggestions. It consists of two main
19
+ components:
20
+
21
+ 1. The `@replace_me` decorator: Marks functions as deprecated and suggests
22
+ replacements with actual argument values substituted.
23
+
24
+ 2. Migration tools: Command-line utilities to automatically update codebases
25
+ by replacing deprecated function calls with their suggested replacements.
26
+
27
+ Basic Usage:
28
+ Mark a deprecated function::
29
+
30
+ from dissolve import replace_me
31
+
32
+ @replace_me(since="2.0.0")
33
+ def old_function(x, y):
34
+ return new_function(x, y, mode="legacy")
35
+
36
+ Migrate a codebase::
37
+
38
+ $ dissolve migrate myproject/*.py --write
39
+
40
+ Remove decorators after migration::
41
+
42
+ $ dissolve remove myproject/*.py --before 3.0.0 --write
43
+
44
+ See the documentation for more detailed examples and advanced usage.
45
+ """
46
+
47
+ __version__: tuple[int, int, int] = (0, 1, 0)
48
+
49
+
50
+ __all__ = ["migrate", "replace_me"]
51
+
52
+
53
+ from . import migrate
54
+ from .decorators import replace_me
@@ -0,0 +1,203 @@
1
+ # Copyright (C) 2022 Jelmer Vernooij <jelmer@samba.org>
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Command-line interface for the dissolve tool.
16
+
17
+ This module provides the entry point for the dissolve CLI, which offers
18
+ commands for:
19
+
20
+ - `migrate`: Automatically replace deprecated function calls with their
21
+ suggested replacements in Python source files.
22
+ - `remove`: Remove @replace_me decorators from source files, optionally
23
+ filtering by version.
24
+
25
+ Run `dissolve --help` for more information on available commands and options.
26
+ """
27
+
28
+
29
+
30
+ def main(argv: list[str] | None = None) -> int:
31
+ """Main entry point for the dissolve command-line interface.
32
+
33
+ Args:
34
+ argv: Command-line arguments. If None, uses sys.argv[1:].
35
+
36
+ Returns:
37
+ Exit code: 0 for success, 1 for errors.
38
+
39
+ Example:
40
+ Run from command line::
41
+
42
+ $ python -m dissolve migrate myfile.py
43
+ $ python -m dissolve remove myfile.py --all --write
44
+ """
45
+ import argparse
46
+ import ast
47
+
48
+ from .migrate import migrate_file_with_imports
49
+ from .remove import remove_from_file
50
+
51
+ parser = argparse.ArgumentParser(
52
+ description="Dissolve - Replace deprecated API usage"
53
+ )
54
+ subparsers = parser.add_subparsers(dest="command", help="Commands")
55
+
56
+ # Migrate command
57
+ migrate_parser = subparsers.add_parser(
58
+ "migrate", help="Migrate Python files by inlining deprecated function calls"
59
+ )
60
+ migrate_parser.add_argument("files", nargs="+", help="Python files to migrate")
61
+ migrate_parser.add_argument(
62
+ "-w",
63
+ "--write",
64
+ action="store_true",
65
+ help="Write changes back to files (default: print to stdout)",
66
+ )
67
+ migrate_parser.add_argument(
68
+ "--check",
69
+ action="store_true",
70
+ help="Check if files need migration without modifying them (exit 1 if changes needed)",
71
+ )
72
+
73
+ # Remove command
74
+ remove_parser = subparsers.add_parser(
75
+ "remove", help="Remove @replace_me decorators from Python files"
76
+ )
77
+ remove_parser.add_argument("files", nargs="+", help="Python files to process")
78
+ remove_parser.add_argument(
79
+ "-w",
80
+ "--write",
81
+ action="store_true",
82
+ help="Write changes back to files (default: print to stdout)",
83
+ )
84
+ remove_parser.add_argument(
85
+ "--before",
86
+ metavar="VERSION",
87
+ help="Remove decorators with version older than this",
88
+ )
89
+ remove_parser.add_argument(
90
+ "--all",
91
+ action="store_true",
92
+ help="Remove all @replace_me decorators regardless of version",
93
+ )
94
+ remove_parser.add_argument(
95
+ "--check",
96
+ action="store_true",
97
+ help="Check if files have removable decorators without modifying them (exit 1 if changes needed)",
98
+ )
99
+
100
+ args = parser.parse_args(argv)
101
+
102
+ if args.command == "migrate":
103
+ if args.check and args.write:
104
+ parser.error("--check and --write cannot be used together")
105
+
106
+ needs_migration = False
107
+ for filepath in args.files:
108
+ try:
109
+ with open(filepath) as f:
110
+ original = f.read()
111
+ result = migrate_file_with_imports(filepath, write=False)
112
+
113
+ if args.check:
114
+ # Check mode: just report if changes are needed
115
+ if result != original:
116
+ print(f"{filepath}: needs migration")
117
+ needs_migration = True
118
+ else:
119
+ print(f"{filepath}: up to date")
120
+ elif args.write:
121
+ # Write mode: update file if changed
122
+ if result != original:
123
+ with open(filepath, "w") as f:
124
+ f.write(result)
125
+ print(f"Modified: {filepath}")
126
+ else:
127
+ print(f"Unchanged: {filepath}")
128
+ else:
129
+ # Default: print to stdout
130
+ print(f"# Migrated: {filepath}")
131
+ print(result)
132
+ print()
133
+ except Exception as e:
134
+ import sys
135
+
136
+ print(f"Error processing {filepath}: {e}", file=sys.stderr)
137
+ return 1
138
+
139
+ # In check mode, exit with code 1 if any files need migration
140
+ if args.check and needs_migration:
141
+ return 1
142
+ elif args.command == "remove":
143
+ if args.check and args.write:
144
+ parser.error("--check and --write cannot be used together")
145
+
146
+ needs_removal = False
147
+ for filepath in args.files:
148
+ try:
149
+ with open(filepath) as f:
150
+ original = f.read()
151
+ result = remove_from_file(
152
+ filepath,
153
+ before_version=args.before,
154
+ remove_all=args.all,
155
+ write=False,
156
+ )
157
+
158
+ if args.check:
159
+ # Check mode: just report if changes are needed
160
+ # Note: AST transformations may normalize whitespace, so we need to
161
+ # check if there are actual semantic changes beyond formatting
162
+ original_tree = ast.parse(original)
163
+ result_tree = ast.parse(result)
164
+
165
+ # Simple check: compare AST dumps (this ignores formatting)
166
+ if ast.dump(original_tree) != ast.dump(result_tree):
167
+ print(f"{filepath}: has removable decorators")
168
+ needs_removal = True
169
+ else:
170
+ print(f"{filepath}: no removable decorators")
171
+ elif args.write:
172
+ # Write mode: update file if changed
173
+ if result != original:
174
+ with open(filepath, "w") as f:
175
+ f.write(result)
176
+ print(f"Modified: {filepath}")
177
+ else:
178
+ print(f"Unchanged: {filepath}")
179
+ else:
180
+ # Default: print to stdout
181
+ print(f"# Removed decorators from: {filepath}")
182
+ print(result)
183
+ print()
184
+ except Exception as e:
185
+ import sys
186
+
187
+ print(f"Error processing {filepath}: {e}", file=sys.stderr)
188
+ return 1
189
+
190
+ # In check mode, exit with code 1 if any files need removal
191
+ if args.check and needs_removal:
192
+ return 1
193
+ else:
194
+ parser.print_help()
195
+ return 1
196
+
197
+ return 0
198
+
199
+
200
+ if __name__ == "__main__":
201
+ import sys
202
+
203
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,103 @@
1
+ # Copyright (C) 2022 Jelmer Vernooij <jelmer@samba.org>
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """AST utilities for parameter substitution in expressions."""
16
+
17
+ import ast
18
+ from collections.abc import Mapping
19
+ from typing import Any
20
+
21
+
22
+ class ParameterSubstitutor(ast.NodeTransformer):
23
+ """Replace parameter names in an AST with their actual values."""
24
+
25
+ def __init__(self, param_map: Mapping[str, ast.AST]):
26
+ """Initialize with a mapping of parameter names to AST nodes.
27
+
28
+ Args:
29
+ param_map: Dictionary mapping parameter names to their AST representations
30
+ """
31
+ self.param_map = param_map
32
+
33
+ def visit_Name(self, node: ast.Name) -> ast.AST:
34
+ """Replace Name nodes that match parameters."""
35
+ if node.id in self.param_map:
36
+ # Return a copy of the replacement node
37
+ replacement = self.param_map[node.id]
38
+ if isinstance(replacement, ast.AST):
39
+ return ast.copy_location(replacement, node)
40
+ else:
41
+ # If it's a value, create a Constant node
42
+ return ast.copy_location(ast.Constant(value=replacement), node)
43
+ return self.generic_visit(node)
44
+
45
+
46
+ def substitute_parameters(
47
+ expr_ast: ast.AST, param_map: Mapping[str, ast.AST]
48
+ ) -> ast.AST:
49
+ """Substitute parameters in an AST expression.
50
+
51
+ Args:
52
+ expr_ast: The AST expression containing parameter references
53
+ param_map: Dictionary mapping parameter names to their AST representations
54
+
55
+ Returns:
56
+ New AST with parameters substituted
57
+ """
58
+ substitutor = ParameterSubstitutor(param_map)
59
+ return substitutor.visit(expr_ast)
60
+
61
+
62
+ def create_ast_from_value(value: Any) -> ast.AST:
63
+ """Create an AST node from a Python value.
64
+
65
+ Args:
66
+ value: Python value to convert to AST
67
+
68
+ Returns:
69
+ AST representation of the value
70
+ """
71
+ return ast.Constant(value=value)
72
+
73
+
74
+ def substitute_in_expression(expr_str: str, param_map: dict[str, Any]) -> str:
75
+ """Substitute parameters in a string expression using AST.
76
+
77
+ Args:
78
+ expr_str: Expression string with parameters
79
+ param_map: Dictionary mapping parameter names to their values
80
+
81
+ Returns:
82
+ Expression string with parameters substituted
83
+ """
84
+ try:
85
+ # Parse the expression
86
+ expr_ast = ast.parse(expr_str, mode="eval").body
87
+
88
+ # Convert values to AST nodes
89
+ ast_param_map = {
90
+ name: create_ast_from_value(value)
91
+ if not isinstance(value, ast.AST)
92
+ else value
93
+ for name, value in param_map.items()
94
+ }
95
+
96
+ # Substitute parameters
97
+ result_ast = substitute_parameters(expr_ast, ast_param_map)
98
+
99
+ # Convert back to string
100
+ return ast.unparse(result_ast)
101
+ except Exception:
102
+ # Fallback to original if AST manipulation fails
103
+ return expr_str