package-scripts 0.2.3__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,255 @@
1
+ /init.sh
2
+ *.tmp
3
+ .idea
4
+ build/
5
+ dist/
6
+ sdist/
7
+ /tests/fixtures/output/
8
+ /extras/docs/site/
9
+
10
+ # Source: https://github.com/github/gitignor
11
+
12
+ # Byte-compiled / optimized / DLL files
13
+ __pycache__/
14
+ *.py[cod]
15
+ *$py.class
16
+
17
+ # C extensions
18
+ *.so
19
+
20
+ # Distribution / packaging
21
+ .Python
22
+ develop-eggs/
23
+ downloads/
24
+ eggs/
25
+ .eggs/
26
+ lib/
27
+ bin/
28
+ lib64/
29
+ parts/
30
+ var/
31
+ wheels/
32
+ share/python-wheels/
33
+ *.egg-info/
34
+ .installed.cfg
35
+ *.egg
36
+ MANIFEST
37
+
38
+ # PyInstaller
39
+ # Usually these files are written by a python script from a template
40
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
41
+ *.manifest
42
+ *.spec
43
+
44
+ # Installer logs
45
+ pip-log.txt
46
+ pip-delete-this-directory.txt
47
+
48
+ # Unit test / coverage reports
49
+ htmlcov/
50
+ .tox/
51
+ .nox/
52
+ .coverage
53
+ .coverage.*
54
+ .cache
55
+ nosetests.xml
56
+ coverage.xml
57
+ *.cover
58
+ *.py,cover
59
+ .hypothesis/
60
+ .pytest_cache/
61
+ cover/
62
+
63
+ # Translations
64
+ *.mo
65
+ *.pot
66
+
67
+ # Django stuff:
68
+ *.log
69
+ local_settings.py
70
+ db.sqlite3
71
+ db.sqlite3-journal
72
+
73
+ # Flask stuff:
74
+ instance/
75
+ .webassets-cache
76
+
77
+ # Scrapy stuff:
78
+ .scrapy
79
+
80
+ # Sphinx documentation
81
+ extras/docs/_build/
82
+
83
+ # PyBuilder
84
+ .pybuilder/
85
+ target/
86
+
87
+ # Jupyter Notebook
88
+ .ipynb_checkpoints
89
+
90
+ # IPython
91
+ profile_default/
92
+ ipython_config.py
93
+
94
+ # pyenv
95
+ # For a library or package, you might want to ignore these files since the code is
96
+ # intended to run in multiple environments; otherwise, check them in:
97
+ .python-version
98
+
99
+ # pipenv
100
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
101
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
102
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
103
+ # install all needed dependencies.
104
+ Pipfile.lock
105
+
106
+ # poetry
107
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
108
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
109
+ # commonly ignored for libraries.
110
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
111
+ poetry.lock
112
+
113
+ # pdm
114
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
115
+ pdm.lock
116
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
117
+ # in version control.
118
+ # https://pdm.fming.dev/#use-with-ide
119
+ .pdm.toml
120
+
121
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
122
+ __pypackages__/
123
+
124
+ # Celery stuff
125
+ celerybeat-schedule
126
+ celerybeat.pid
127
+
128
+ # SageMath parsed files
129
+ *.sage.py
130
+
131
+ # Environments
132
+ .env
133
+ .venv
134
+ env/
135
+ venv/
136
+ ENV/
137
+ env.bak/
138
+ venv.bak/
139
+
140
+ # Spyder project settings
141
+ .spyderproject
142
+ .spyproject
143
+
144
+ # Rope project settings
145
+ .ropeproject
146
+
147
+ # mkdocs documentation
148
+ /site
149
+
150
+ # mypy
151
+ .mypy_cache/
152
+ .dmypy.json
153
+ dmypy.json
154
+
155
+ # Pyre type checker
156
+ .pyre/
157
+
158
+ # pytype static type analyzer
159
+ .pytype/
160
+
161
+ # Cython debug symbols
162
+ cython_debug/
163
+
164
+ # PyCharm
165
+ .idea/
166
+
167
+
168
+ ## MacOS
169
+ # General
170
+ .DS_Store
171
+ .AppleDouble
172
+ .LSOverride
173
+
174
+ # Icon must end with two \r
175
+ Icon
176
+
177
+ # Thumbnails
178
+ ._*
179
+
180
+ # Files that might appear in the root of a volume
181
+ .DocumentRevisions-V100
182
+ .fseventsd
183
+ .Spotlight-V100
184
+ .TemporaryItems
185
+ .Trashes
186
+ .VolumeIcon.icns
187
+ .com.apple.timemachine.donotpresent
188
+
189
+ # Directories potentially created on remote AFP share
190
+ .AppleDB
191
+ .AppleDesktop
192
+ Network Trash Folder
193
+ Temporary Items
194
+ .apdisk
195
+
196
+ ## Windows
197
+ # Windows thumbnail cache files
198
+ Thumbs.db
199
+ Thumbs.db:encryptable
200
+ ehthumbs.db
201
+ ehthumbs_vista.db
202
+
203
+ # Dump file
204
+ *.stackdump
205
+
206
+ # Folder config file
207
+ [Dd]esktop.ini
208
+
209
+ # Recycle Bin used on file shares
210
+ $RECYCLE.BIN/
211
+
212
+ # Windows Installer files
213
+ *.cab
214
+ *.msi
215
+ *.msix
216
+ *.msm
217
+ *.msp
218
+
219
+ # Windows shortcuts
220
+ *.lnk
221
+
222
+ ## Linux
223
+ *~
224
+
225
+ # temporary files which can be created if a process still has a handle open of a deleted file
226
+ .fuse_hidden*
227
+
228
+ # KDE directory preferences
229
+ .directory
230
+
231
+ # Linux trash folder which might appear on any partition or disk
232
+ .Trash-*
233
+
234
+ # .nfs files are created when an open file is removed but is still being accessed
235
+ .nfs*
236
+
237
+ ## Vim
238
+ # Swap
239
+ [._]*.s[a-v][a-z]
240
+ !*.svg # comment out if you don't need vector files
241
+ [._]*.sw[a-p]
242
+ [._]s[a-rt-v][a-z]
243
+ [._]ss[a-gi-z]
244
+ [._]sw[a-p]
245
+
246
+ # Session
247
+ Session.vim
248
+ Sessionx.vim
249
+
250
+ # Temporary
251
+ .netrwhist
252
+ # Auto-generated tag files
253
+ tags
254
+ # Persistent undo
255
+ [._]*.un~
@@ -0,0 +1,3 @@
1
+
2
+ - common.project_root needs to be derived from PWD
3
+ -
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cameron Ratchford
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: package-scripts
3
+ Version: 0.2.3
4
+ Author-email: Cam Ratchford <camratchford@gmail.com>
5
+ Project-URL: Homepage, https://github.com/camratchford/package-scripts
6
+ Project-URL: Source, https://github.com/camratchford/package-scripts
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Natural Language :: English
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: typer
21
+ Requires-Dist: ruff
22
+ Requires-Dist: isort
23
+ Requires-Dist: pytest
24
+ Requires-Dist: build
25
+ Requires-Dist: setuptools
26
+ Requires-Dist: packaging
27
+ Requires-Dist: twine
28
+ Dynamic: license-file
29
+
30
+ # Miscelaneous Scripts
31
+
32
+ Scripts for frequently performed Python development tasks.
33
+
34
+ - run-build - Build and (optionally) publish a package to PyPI
35
+ - run-deploy - Generate and install a systemd unit file with the provided parameters
36
+ - run-test - Run pytest
37
+ - run-format - Run isort, ruff format, and ruff check.
38
+ - run-version-bump - Update pyproject.toml with a new version, pushing the new version's git tags
39
+
@@ -0,0 +1,10 @@
1
+ # Miscelaneous Scripts
2
+
3
+ Scripts for frequently performed Python development tasks.
4
+
5
+ - run-build - Build and (optionally) publish a package to PyPI
6
+ - run-deploy - Generate and install a systemd unit file with the provided parameters
7
+ - run-test - Run pytest
8
+ - run-format - Run isort, ruff format, and ruff check.
9
+ - run-version-bump - Update pyproject.toml with a new version, pushing the new version's git tags
10
+
File without changes
@@ -0,0 +1,123 @@
1
+ import shutil
2
+ from pathlib import Path
3
+ from typing import Annotated
4
+
5
+ import twine.commands.upload
6
+ from rich import print as rprint
7
+ from twine.settings import Settings
8
+ from typer import Option, Typer, prompt
9
+
10
+ import build
11
+
12
+ from .common import run
13
+
14
+ cli = Typer(pretty_exceptions_enable=False)
15
+ default_dist_path = Path.cwd() / "dist"
16
+
17
+
18
+ def get_default_branch():
19
+ git_process = run("git config get --default main init.defaultbranch")
20
+
21
+ if git_process.returncode:
22
+ rprint(f"[bold red]Error while getting default git branch: {git_process.stderr}[/]")
23
+ raise SystemExit(git_process.returncode)
24
+
25
+ return git_process.stdout
26
+
27
+
28
+ def get_current_branch():
29
+ git_process = run("git rev-parse --abbrev-ref HEAD")
30
+
31
+ if git_process.returncode:
32
+ rprint(f"[bold red]Error while getting current git branch: {git_process.stderr}[/]")
33
+ raise SystemExit(git_process.returncode)
34
+
35
+ return git_process.stdout
36
+
37
+
38
+ def check_last_commit_for_tag():
39
+ git_process = run("git tag --points-at $(git rev-parse HEAD)")
40
+
41
+ if git_process.returncode:
42
+ rprint(f"[bold red]Error while getting last git log entry: {git_process.stderr}[/]")
43
+ raise SystemExit(git_process.returncode)
44
+
45
+ if not git_process.stdout:
46
+ return False
47
+
48
+ return True
49
+
50
+
51
+ def build_python_package(dist_dir: Path):
52
+ if dist_dir.exists():
53
+ shutil.rmtree(dist_dir)
54
+ dist_dir.mkdir(parents=True, exist_ok=True)
55
+
56
+ builder = build.ProjectBuilder(Path.cwd())
57
+ builder.build("wheel", output_directory=str(dist_dir.absolute()))
58
+ builder.build("sdist", output_directory=str(dist_dir.absolute()))
59
+
60
+ dist_files = [str(p) for p in dist_dir.iterdir()]
61
+
62
+ return dist_files
63
+
64
+
65
+ def publish(dist_files: list[str], prompt_for_token: bool = False):
66
+ default_branch = get_default_branch()
67
+ current_branch = get_current_branch()
68
+ if current_branch != default_branch:
69
+ rprint(f"[bold red]Cannot publish from a branch that is not {default_branch}.[/]")
70
+ raise SystemExit(1)
71
+
72
+ if not check_last_commit_for_tag():
73
+ rprint(
74
+ f"[bold red]Cannot publish with stale tags, "
75
+ f"last commit on {default_branch} does not contain any new tags.[/]"
76
+ )
77
+ raise SystemExit(1)
78
+
79
+ settings_kwargs = {"verbose": True, "non_interactive": True}
80
+ if prompt_for_token:
81
+ prompted_token = None
82
+ while prompted_token is None:
83
+ prompted_token = prompt("Enter PyPI token", hide_input=True, confirmation_prompt=True)
84
+ settings_kwargs.update(password=prompted_token, username="__token__")
85
+
86
+ twine.commands.upload.upload(
87
+ Settings(
88
+ **settings_kwargs,
89
+ ),
90
+ dist_files,
91
+ )
92
+
93
+
94
+ @cli.command(help="Build and (optionally) publish a package to PyPI")
95
+ def main(
96
+ dist_dir: Annotated[
97
+ Path, Option("--dist", help="Where the built packages should go", dir_okay=True, file_okay=False)
98
+ ] = default_dist_path,
99
+ publish_to_pypi: Annotated[
100
+ bool,
101
+ Option(
102
+ "--publish",
103
+ help=(
104
+ "Publish to PyPi "
105
+ "[dim]"
106
+ "(If --prompt-for-token is not provided, "
107
+ "you must authenticate with PyPI by some other means. "
108
+ "See Twine's [link=https://twine.readthedocs.io/en/latest/]documentation[/link] "
109
+ "for details)"
110
+ "[/]"
111
+ ),
112
+ ),
113
+ ] = False,
114
+ prompt_for_token: Annotated[bool, Option("--prompt-for-token", help="Prompt for PyPI token.")] = False,
115
+ ):
116
+ dist_files = build_python_package(dist_dir)
117
+ if publish_to_pypi:
118
+ publish(dist_files, prompt_for_token)
119
+
120
+
121
+ if __name__ == "__main__":
122
+ ...
123
+ #cli()
@@ -0,0 +1,47 @@
1
+ import subprocess
2
+ from pathlib import Path
3
+
4
+ from typer import BadParameter, CallbackParam, Context
5
+
6
+ this_directory = Path(__file__).parent
7
+ package_name = __name__.split(".")[0]
8
+
9
+
10
+ def run(cmd):
11
+ """
12
+ Runs shell commands in the project's root directory
13
+
14
+ Args:
15
+ cmd (str):
16
+ The shell command that will be run
17
+
18
+ Returns:
19
+ subprocess.CompletedProcess
20
+ """
21
+
22
+ return subprocess.run(
23
+ cmd,
24
+ shell=True,
25
+ text=True,
26
+ cwd=Path.cwd(),
27
+ capture_output=True,
28
+ check=False,
29
+ )
30
+
31
+
32
+ def create_mutually_exclusive_callback(size: int = 1):
33
+ """
34
+ From this GitHub issue comment: https://github.com/fastapi/typer/issues/140#issuecomment-898937671
35
+ """
36
+ group = set()
37
+
38
+ def callback(_: Context, param: CallbackParam, value: str):
39
+ # Add cli option to group if it was called with a value
40
+ if value is not None and param.name not in group:
41
+ group.add(param.name)
42
+ if len(group) > size - 1:
43
+ raise BadParameter(f"Option '{param.name}' is mutually exclusive with option '{group.pop()}'")
44
+
45
+ return value
46
+
47
+ return callback
@@ -0,0 +1,158 @@
1
+ from os import getuid
2
+ from pathlib import Path
3
+ from pwd import getpwall
4
+ from typing import Annotated
5
+
6
+ from rich import print as rprint
7
+ from rich.console import Console
8
+ from rich.syntax import Syntax
9
+ from typer import Option, Typer
10
+
11
+ cli = Typer(pretty_exceptions_enable=False, no_args_is_help=True)
12
+
13
+
14
+ create_user_cmd_template = """sudo useradd \\
15
+ --system \\
16
+ --shell /bin/bash \\
17
+ --home-dir {service_pwd} \\
18
+ {service_name}"""
19
+
20
+ unit_file_template = """[Unit]
21
+ Description="{service_name}"
22
+ After=network.target
23
+
24
+ [Service]
25
+ Type=simple
26
+ User={service_name}
27
+ WorkingDirectory={service_pwd}
28
+ ExecStart={service_exec}
29
+ Restart=on-failure
30
+ RestartSec=5
31
+
32
+ Environment="{service_env_vars}"
33
+
34
+ [Install]
35
+ WantedBy=multi-user.target"""
36
+
37
+
38
+ start_service_template = (
39
+ r"sudo systemctl daemon-reload && sudo systemctl enable {unit_file_name} && sudo systemctl start {unit_file_name}"
40
+ )
41
+
42
+ this_dir = Path(__file__).parent
43
+ default_project_root = this_dir.parent if this_dir.parent.joinpath("pyproject.toml").exists() else Path().cwd()
44
+
45
+ backslash = "[#fe885b]\\ [/#fe885b]"
46
+ tab = "[white] [/white]" # It will collapse the spaces otherwise
47
+
48
+ epilogue = f"""
49
+ [#e0]Example:\n\n\n
50
+ [dim]# An imaginary webapp called my-app[/dim] \n
51
+ run-deploy {backslash} \n
52
+ {tab}--service-name my-app {backslash} \n
53
+ {tab}--working-directory /opt/my-app {backslash} \n
54
+ {tab}--exec "my-app --port 80 --hostname '0.0.0.0'" {backslash} \n
55
+ {tab}-v "PATH=/opt/my-app/venv" {backslash} \n
56
+ {tab}-v "MY_APP_PORT=8080" {backslash} \n
57
+ {tab}-v "MY_APP_CONFIG_FILE_PATH=/opt/my-app/config.yml"
58
+ """
59
+
60
+
61
+ @cli.command(help="Generate and install a systemd unit file with the provided parameters", epilog=epilogue)
62
+ def main(
63
+ service_name: Annotated[
64
+ str,
65
+ Option(
66
+ "--service-name",
67
+ help="The name of the service. (determines: systemd serivce name, unit file name, service account name)\n\n"
68
+ '[magenta dim]example: --service-name "my-app"[/]',
69
+ ),
70
+ ],
71
+ service_pwd: Annotated[
72
+ Path,
73
+ Option(
74
+ "--working-directory",
75
+ help="The working directory of the service's process\n\n"
76
+ '[magenta dim]example: --working-directory "/opt/my_app"[/]',
77
+ dir_okay=True,
78
+ file_okay=False,
79
+ ),
80
+ ],
81
+ service_exec: Annotated[
82
+ str,
83
+ Option(
84
+ "--exec",
85
+ help="The command and args that will be executed when the service is started. "
86
+ "Nested quotes must be escaped.\n\n"
87
+ "[magenta dim]example: --exec \"/opt/my_app/venv/bin/my_app --port 80 --host '0.0.0.0'\"[/]",
88
+ ),
89
+ ],
90
+ service_env_var: Annotated[
91
+ list[str],
92
+ Option(
93
+ "-v",
94
+ "--environment-variable",
95
+ help="Supply env vars to the service. Can be used multiple times. Values should resemble KEY=VALUE.\n\n"
96
+ "[magenta dim]example: "
97
+ '-v "MY_APP_CONFIG_FILE_PATH=/opt/my_app/config.yaml" '
98
+ '-v "MY_APP_PORT=8080"[/]',
99
+ ),
100
+ ] = (),
101
+ unit_file_path: Annotated[
102
+ Path,
103
+ Option(
104
+ "--unit-file-output-path",
105
+ help="The output path of the generated systemd unit file. "
106
+ "[dim]\\[default: /etc/systemd/system/{service-name}.service]",
107
+ exists=False,
108
+ ),
109
+ ] = None,
110
+ user_must_exist: Annotated[
111
+ bool,
112
+ Option(help="Check for the service account with the name {service-name} before creating the unit file\n\n"),
113
+ ] = True,
114
+ dry_run: Annotated[
115
+ bool,
116
+ Option("--dry-run", help="Don't generate a unit file, just print it to stdout"),
117
+ ] = False,
118
+ ):
119
+ if not dry_run and not unit_file_path and getuid() != 0:
120
+ rprint("[bold red]This script must be run as root[/]")
121
+ raise SystemExit(1)
122
+
123
+ if user_must_exist and service_name not in [pw.pw_name for pw in getpwall()]:
124
+ create_user_cmd = create_user_cmd_template.format(service_pwd=service_pwd, service_name=service_name)
125
+ rprint(
126
+ f"[bold red]The '{service_name}' service account has not been created yet.[/]\n"
127
+ f"Use the [dim cyan]--no-user-must-exist[/] option or run:[dim]\n{create_user_cmd}[/]\n"
128
+ )
129
+ if not dry_run:
130
+ raise SystemExit(1)
131
+
132
+ unit_file_content = unit_file_template.format(
133
+ service_name=service_name,
134
+ service_pwd=service_pwd.as_posix(),
135
+ service_exec=service_exec,
136
+ service_env_vars=" ".join(service_env_var),
137
+ )
138
+
139
+ if dry_run:
140
+ temp_file = Path("/tmp/{service_name}.service")
141
+ temp_file.write_text(unit_file_content)
142
+ console = Console()
143
+ syntax = Syntax.from_path(temp_file, theme="material", background_color="default")
144
+ console.print(syntax)
145
+ return
146
+
147
+ if not unit_file_path:
148
+ unit_file_path = Path(f"/etc/systemd/system/{service_name}.service")
149
+
150
+ unit_file_path.write_text(unit_file_content)
151
+ unit_file_path.chmod(mode=0o600)
152
+
153
+ start_service_cmd = start_service_template.format(unit_file_name=unit_file_path.name)
154
+ rprint(f"To enable the service run:\n[dim]{start_service_cmd}[/]")
155
+
156
+
157
+ if __name__ == "__main__":
158
+ cli()
@@ -0,0 +1,50 @@
1
+ from pathlib import Path
2
+ from subprocess import CompletedProcess
3
+ from typing import Annotated
4
+
5
+ from rich import print as rprint
6
+ from typer import Argument, Option, Typer
7
+
8
+ from .common import run
9
+
10
+ cli = Typer(pretty_exceptions_enable=False)
11
+
12
+
13
+ @cli.command(help="Run isort, ruff format, and ruff check.")
14
+ def main(
15
+ directories: Annotated[
16
+ list[Path], Argument(help="List of directories to format and lint", dir_okay=True, file_okay=False)
17
+ ] = (Path.cwd(),),
18
+ test_mode: Annotated[
19
+ bool, Option("--test-mode", help="Exits with error if formatter or linter encounter violations")
20
+ ] = False,
21
+ ):
22
+ dir_arg = " ".join(d.as_posix() for d in directories)
23
+
24
+ check_test_arg = format_test_arg = isort_test_arg = ""
25
+ if test_mode:
26
+ check_test_arg = "--exit-non-zero-on-fix"
27
+ format_test_arg = "--check --exit-non-zero-on-fix"
28
+ isort_test_arg = "--check"
29
+
30
+ messages = ""
31
+
32
+ isort_process: CompletedProcess = run(f"isort --atomic {isort_test_arg} {dir_arg}")
33
+ if isort_process.returncode:
34
+ messages += f"[bold yellow]isort:[/]\n{isort_process.stderr}\n"
35
+
36
+ check_process: CompletedProcess = run(f"ruff check --show-fixes --fix {check_test_arg} {dir_arg}")
37
+ if check_process.returncode:
38
+ messages += f"[bold yellow]ruff check:[/]\n{check_process.stdout}\n"
39
+
40
+ format_process: CompletedProcess = run(f"ruff format {format_test_arg} {dir_arg}")
41
+ if format_process.returncode:
42
+ messages += f"[bold yellow]ruff format:[/]\n{format_process.stdout}"
43
+
44
+ if messages:
45
+ rprint("[bold red]Formater / Linter errors:[/]\n\n" + messages)
46
+ raise SystemExit(1)
47
+
48
+
49
+ if __name__ == "__main__":
50
+ cli()
@@ -0,0 +1,32 @@
1
+ from pathlib import Path
2
+ from typing import Annotated
3
+
4
+ from rich import print as rprint
5
+ from typer import Argument, Option, Typer
6
+
7
+ from .common import run
8
+
9
+ cli = Typer(pretty_exceptions_enable=False)
10
+
11
+
12
+ @cli.command(help="Run pytest")
13
+ def main(
14
+ file_or_dir: Annotated[
15
+ Path, Argument(help="Location of directory containing tests", dir_okay=True, file_okay=True)
16
+ ] = Path.cwd() / "tests",
17
+ from_last_failed: Annotated[
18
+ bool, Option("--from-last-failed", help="Exit on test failure and continue from last failing test next time")
19
+ ] = False,
20
+ ):
21
+ from_last_failed_arg = ""
22
+ if from_last_failed:
23
+ from_last_failed_arg = "--stepwise"
24
+ process = run(f"pytest {from_last_failed_arg} {file_or_dir.as_posix()}")
25
+
26
+ if process.returncode:
27
+ rprint("[bold red]pytest errors:[/]\n\n" + process.stderr.rstrip() + "\n")
28
+ raise SystemExit(process.returncode)
29
+
30
+
31
+ if __name__ == "__main__":
32
+ cli()
@@ -0,0 +1,136 @@
1
+ import re
2
+ from pathlib import Path
3
+ from typing import Annotated
4
+
5
+ from packaging.version import Version
6
+ from rich import print as rprint
7
+ from typer import Option, Typer
8
+
9
+ from .common import create_mutually_exclusive_callback, run
10
+
11
+ cli = Typer(pretty_exceptions_enable=False, no_args_is_help=True)
12
+
13
+ pyproject_dot_toml = Path.cwd() / "pyproject.toml"
14
+ mutually_exlclusive_callback = create_mutually_exclusive_callback(2)
15
+
16
+
17
+ def get_current_version() -> Version:
18
+ content = pyproject_dot_toml.read_text()
19
+ match = re.search(r'^version\s*=\s*["\'](.+?)["\']', content, re.MULTILINE)
20
+ if not match:
21
+ print("Error: Version not found in pyproject.toml")
22
+ exit(1)
23
+ return Version(match.group(1))
24
+
25
+
26
+ def get_new_version(version: Version, magnitude: str) -> str:
27
+ if magnitude == "dev":
28
+ dev_ver = version.dev + 1 if version.dev else 0
29
+ return f"{version.major}.{version.minor}.{version.micro}.dev{dev_ver}"
30
+
31
+ elif magnitude == "patch":
32
+ return f"{version.major}.{version.minor}.{version.micro + 1}"
33
+
34
+ elif magnitude == "minor":
35
+ return f"{version.major}.{version.minor + 1}.0"
36
+
37
+ elif magnitude == "major":
38
+ return f"{version.major + 1}.0.0"
39
+
40
+ else:
41
+ rprint(f"[bold red] Invalid version bump magnitude:[/] {magnitude}\nChoose one of: dev, patch, minor, major")
42
+ raise SystemExit(1)
43
+
44
+
45
+ def set_new_version(new_version: str):
46
+ content = pyproject_dot_toml.read_text()
47
+ new_content = re.sub(
48
+ r'(^version\s*=\s*["\'])(.+?)(["\'])',
49
+ rf'version = "{new_version}"',
50
+ content,
51
+ flags=re.MULTILINE,
52
+ )
53
+ pyproject_dot_toml.write_text(new_content)
54
+
55
+
56
+ def git_tag(version: str):
57
+ for cmd in [
58
+ run(f"git add {pyproject_dot_toml}"),
59
+ run(f'git commit -m "Release {version}"'),
60
+ run(f"git tag v{version}"),
61
+ run("git push"),
62
+ run(f"git push origin v{version}"),
63
+ ]:
64
+ if cmd.returncode:
65
+ cmd_message = cmd.stdout + cmd.stderr
66
+ rprint(f"[bold red]Error running git cmd '{cmd.args}':\n" + cmd_message)
67
+ raise SystemExit(cmd.returncode)
68
+
69
+
70
+ @cli.command(help="Update pyproject.toml with a new version, pushing the new version as a git tag")
71
+ def main(
72
+ dev: Annotated[
73
+ bool,
74
+ Option(
75
+ help="Bump dev version: Maj.Min.Pat.devDev → Maj.Min.Pat.dev{Dev+1}",
76
+ callback=mutually_exlclusive_callback,
77
+ ),
78
+ ] = None,
79
+ patch: Annotated[
80
+ bool,
81
+ Option(
82
+ help="Bump patch version: Maj.Min.Pat → Maj.Min.{Pat+1}",
83
+ callback=mutually_exlclusive_callback,
84
+ ),
85
+ ] = None,
86
+ minor: Annotated[
87
+ bool,
88
+ Option(
89
+ help="Bump minor version: Maj.Min.Pat → Maj.{Min+1}.0",
90
+ callback=mutually_exlclusive_callback,
91
+ ),
92
+ ] = None,
93
+ major: Annotated[
94
+ bool,
95
+ Option(
96
+ help="Bump major version: Maj.Min.Pat → {Maj+1}.0.0",
97
+ callback=mutually_exlclusive_callback,
98
+ ),
99
+ ] = None,
100
+ manual: Annotated[
101
+ bool,
102
+ Option(
103
+ help="You've modified pyproject.toml yourself. "
104
+ "Don't auto-increment based on release type. Only run git tag commands.",
105
+ callback=mutually_exlclusive_callback,
106
+ ),
107
+ ] = None,
108
+ dry_run: Annotated[
109
+ bool, Option(help="Only show log messages, do not modify version in any way", is_flag=True)
110
+ ] = False,
111
+ ) -> None:
112
+
113
+ if not pyproject_dot_toml.exists():
114
+ rprint(f"[bold red]Could not find [magenta]{pyproject_dot_toml.as_posix()}. Unable to set version.[/]")
115
+ raise SystemExit(1)
116
+
117
+ version_bump_magnitude = "dev" if dev else "patch" if patch else "minor" if minor else "major" if major else None
118
+
119
+ current_version = get_current_version()
120
+
121
+ if version_bump_magnitude is None:
122
+ print(current_version)
123
+ exit(0)
124
+
125
+ new_version = current_version
126
+ if not manual:
127
+ new_version = get_new_version(current_version, version_bump_magnitude)
128
+
129
+ rprint(f"[#fefefe]Bumping version:\n[#ababef]{current_version} [yellow]→ [blue]{new_version}[/]")
130
+ if not dry_run:
131
+ set_new_version(new_version)
132
+ git_tag(new_version)
133
+
134
+
135
+ if __name__ == "__main__":
136
+ cli()
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: package-scripts
3
+ Version: 0.2.3
4
+ Author-email: Cam Ratchford <camratchford@gmail.com>
5
+ Project-URL: Homepage, https://github.com/camratchford/package-scripts
6
+ Project-URL: Source, https://github.com/camratchford/package-scripts
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Natural Language :: English
10
+ Classifier: Programming Language :: Python
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Operating System :: MacOS
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: typer
21
+ Requires-Dist: ruff
22
+ Requires-Dist: isort
23
+ Requires-Dist: pytest
24
+ Requires-Dist: build
25
+ Requires-Dist: setuptools
26
+ Requires-Dist: packaging
27
+ Requires-Dist: twine
28
+ Dynamic: license-file
29
+
30
+ # Miscelaneous Scripts
31
+
32
+ Scripts for frequently performed Python development tasks.
33
+
34
+ - run-build - Build and (optionally) publish a package to PyPI
35
+ - run-deploy - Generate and install a systemd unit file with the provided parameters
36
+ - run-test - Run pytest
37
+ - run-format - Run isort, ruff format, and ruff check.
38
+ - run-version-bump - Update pyproject.toml with a new version, pushing the new version's git tags
39
+
@@ -0,0 +1,18 @@
1
+ .gitignore
2
+ .todo.md
3
+ LICENSE
4
+ README.md
5
+ pyproject.toml
6
+ package_scripts/__init__.py
7
+ package_scripts/build.py
8
+ package_scripts/common.py
9
+ package_scripts/deploy.py
10
+ package_scripts/format.py
11
+ package_scripts/test.py
12
+ package_scripts/version_bump.py
13
+ package_scripts.egg-info/PKG-INFO
14
+ package_scripts.egg-info/SOURCES.txt
15
+ package_scripts.egg-info/dependency_links.txt
16
+ package_scripts.egg-info/entry_points.txt
17
+ package_scripts.egg-info/requires.txt
18
+ package_scripts.egg-info/top_level.txt
@@ -0,0 +1,6 @@
1
+ [console_scripts]
2
+ run-build = package_scripts.build:cli
3
+ run-deploy = package_scripts.deploy:cli
4
+ run-format = package_scripts.format:cli
5
+ run-test = package_scripts.test:cli
6
+ run-version-bump = package_scripts.version_bump:cli
@@ -0,0 +1,8 @@
1
+ typer
2
+ ruff
3
+ isort
4
+ pytest
5
+ build
6
+ setuptools
7
+ packaging
8
+ twine
@@ -0,0 +1 @@
1
+ package_scripts
@@ -0,0 +1,84 @@
1
+ [project]
2
+ name = "package-scripts"
3
+ version = "0.2.3"
4
+ description = ""
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ authors = [
8
+ {name = "Cam Ratchford", email = "camratchford@gmail.com"},
9
+ ]
10
+
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Natural Language :: English",
15
+ "Programming Language :: Python",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Operating System :: Microsoft :: Windows",
18
+ "Operating System :: POSIX :: Linux",
19
+ "Operating System :: MacOS",
20
+ "Intended Audience :: Developers",
21
+ "Topic :: Software Development :: Libraries :: Python Modules",
22
+ ]
23
+
24
+ dependencies = [
25
+ "typer",
26
+ "ruff",
27
+ "isort",
28
+ "pytest",
29
+ "build",
30
+ "setuptools",
31
+ "packaging",
32
+ "twine",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/camratchford/package-scripts"
37
+ Source = "https://github.com/camratchford/package-scripts"
38
+
39
+ [project.scripts]
40
+ "run-test" = "package_scripts.test:cli"
41
+ "run-build" = "package_scripts.build:cli"
42
+ "run-format" = "package_scripts.format:cli"
43
+ "run-version-bump" = "package_scripts.version_bump:cli"
44
+ "run-deploy" = "package_scripts.deploy:cli"
45
+
46
+ [build-system]
47
+ requires = ["setuptools", "setuptools-scm"]
48
+ build-backend = "setuptools.build_meta"
49
+
50
+ [tool.setuptools]
51
+ packages = ["package_scripts"]
52
+ package-dir = {"package_scripts" = "package_scripts"}
53
+
54
+
55
+ [tool.ruff]
56
+ line-length = 119
57
+ exclude = [
58
+ "tests/fixtures/**/*"
59
+ ]
60
+
61
+ [tool.ruff.lint]
62
+ select = ["E4", "E7", "E9", "F"]
63
+ ignore = []
64
+ fixable = ["ALL"]
65
+ unfixable = []
66
+
67
+ [tool.ruff.format]
68
+ quote-style = "double"
69
+ indent-style = "space"
70
+ skip-magic-trailing-comma = false
71
+ line-ending = "auto"
72
+ docstring-code-format = false
73
+ docstring-code-line-length = "dynamic"
74
+
75
+ [tool.isort]
76
+ profile = "black"
77
+ line_length = 119
78
+ skip_gitignore = true
79
+
80
+ [tool.pytest.ini_options]
81
+ addopts = "-ra -q"
82
+ testpaths = [
83
+ "tests",
84
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+