patchloop 0.2.0__py3-none-any.whl → 0.3.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.
patchloop/cli.py CHANGED
@@ -16,7 +16,7 @@ from patchloop.build import BuildError, resolve_build_args
16
16
  from patchloop.config import BuildConfig, Config, ConfigError, load_config
17
17
  from patchloop.detect import DetectError
18
18
  from patchloop.fixers.base import LockError
19
- from patchloop.git_ops import GitError
19
+ from patchloop.git_ops import GitError, repo_slug
20
20
  from patchloop.github import GitHubError
21
21
  from patchloop.hints import hint_for
22
22
  from patchloop.images import ImageScanError, parse_scanners
@@ -26,6 +26,15 @@ from patchloop.report.json_out import write_scan_json
26
26
  from patchloop.report.sarif import build_sarif, remaining, write_sarif
27
27
  from patchloop.runner import FixError, run_fix
28
28
  from patchloop.scanner import resolve_imports, run_scan
29
+ from patchloop.schedule import (
30
+ ScheduleError,
31
+ check_cron,
32
+ cron_for,
33
+ describe,
34
+ find_target,
35
+ workflow_text,
36
+ write_workflow,
37
+ )
29
38
  from patchloop.sources.base import SourceError
30
39
  from patchloop.worktree import WorktreeError
31
40
 
@@ -368,3 +377,61 @@ def fix_cmd(
368
377
  write_sarif(build_sarif(still_open, lock, lockfile_uri(lock), statuses), sarif_out)
369
378
  console.print(f"SARIF report: {sarif_out}")
370
379
  raise typer.Exit(outcome.exit_code)
380
+
381
+
382
+ @app.command("schedule")
383
+ def schedule_cmd(
384
+ path: PathArg = Path(),
385
+ every: Annotated[
386
+ str, typer.Option("--every", help="How often: day, week or month (the 1st).")
387
+ ] = "week",
388
+ day: Annotated[str, typer.Option("--day", help="Weekday for --every week.")] = "mon",
389
+ at: Annotated[str, typer.Option("--at", help="Time of day, HH:MM in UTC.")] = "06:00",
390
+ cron: Annotated[
391
+ str | None, typer.Option("--cron", help="A cron line instead, e.g. '0 6 * * 1' (UTC).")
392
+ ] = None,
393
+ min_severity: MinSeverityOpt = None,
394
+ force: Annotated[bool, typer.Option("--force", help="Replace an existing workflow.")] = False,
395
+ ) -> None:
396
+ """Run PatchLoop on a schedule on GitHub's servers (writes a GitHub Actions workflow)."""
397
+ if min_severity is not None:
398
+ try:
399
+ Severity(min_severity.upper())
400
+ except ValueError:
401
+ _fail(f"--min-severity must be LOW, MEDIUM, HIGH or CRITICAL, not '{min_severity}'")
402
+ try:
403
+ line = check_cron(cron) if cron else cron_for(every, day, at)
404
+ target = find_target(path)
405
+ written = write_workflow(
406
+ target, workflow_text(line, target.project_rel, min_severity), force
407
+ )
408
+ except ScheduleError as exc:
409
+ _fail(exc)
410
+ rel = written.relative_to(target.repo_root).as_posix()
411
+ try:
412
+ slug = repo_slug(target.repo_root)
413
+ except GitError:
414
+ slug = "OWNER/REPO"
415
+ console.print(f"Wrote {rel}: PatchLoop will run {describe(line)}.", highlight=False)
416
+ console.print("\nNext steps:", highlight=False)
417
+ console.print(
418
+ f"1. Commit and push it: git add {rel} && git commit -m 'Run PatchLoop on a schedule'"
419
+ " && git push",
420
+ highlight=False,
421
+ )
422
+ console.print(
423
+ "2. Once per repo, let GitHub Actions open pull requests: Settings > Actions > General"
424
+ " > Workflow permissions > 'Allow GitHub Actions to create and approve pull requests'"
425
+ f"\n (or: gh api -X PUT repos/{slug}/actions/permissions/workflow"
426
+ " -F can_approve_pull_request_reviews=true)",
427
+ highlight=False,
428
+ )
429
+ console.print(
430
+ f"3. To run it now: gh workflow run {written.name} (or the Actions tab)",
431
+ highlight=False,
432
+ )
433
+ console.print(
434
+ "Optional: PRs opened with the default token don't start your CI; see the README"
435
+ " ('Run it on a schedule') to pass a token that does.",
436
+ highlight=False,
437
+ )
patchloop/github.py CHANGED
@@ -82,6 +82,8 @@ class GhCli:
82
82
  f"cannot open {self.slug} on GitHub",
83
83
  )
84
84
  permission = json.loads(out).get("viewerPermission", "")
85
+ if not permission and not self.user and os.environ.get("GITHUB_ACTIONS") == "true":
86
+ return # a workflow token has no "viewer"; the workflow's permissions decide
85
87
  if permission not in _CAN_PUSH:
86
88
  who = self.user or "the active gh account"
87
89
  raise GitHubError(
patchloop/schedule.py ADDED
@@ -0,0 +1,129 @@
1
+ """``patchloop schedule``: write a GitHub Actions workflow that runs PatchLoop on a timer.
2
+
3
+ GitHub runs it on its own servers, so the schedule keeps working whether or not anyone's
4
+ computer is on. The command only writes the file; committing it is up to the user.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+
13
+ from patchloop import proc
14
+
15
+ ACTION = "AyushSingh012/PatchLoop@v0"
16
+ DAYS = ("sun", "mon", "tue", "wed", "thu", "fri", "sat")
17
+ EVERY = ("day", "week", "month")
18
+
19
+
20
+ class ScheduleError(Exception):
21
+ """The schedule or the place to write the workflow is not usable."""
22
+
23
+
24
+ def cron_for(every: str, day: str, at: str) -> str:
25
+ """A cron line (UTC) for ``every`` day / week (on ``day``) / month (on the 1st) ``at``."""
26
+ m = re.fullmatch(r"([01]?\d|2[0-3]):([0-5]\d)", at.strip())
27
+ if not m:
28
+ raise ScheduleError(f"--at must be HH:MM in 24-hour UTC time, not '{at}'")
29
+ hour, minute = int(m.group(1)), int(m.group(2))
30
+ if every == "day":
31
+ return f"{minute} {hour} * * *"
32
+ if every == "week":
33
+ key = day.strip().lower()[:3]
34
+ if key not in DAYS:
35
+ raise ScheduleError(f"--day must be a weekday (mon … sun), not '{day}'")
36
+ return f"{minute} {hour} * * {DAYS.index(key)}"
37
+ if every == "month":
38
+ return f"{minute} {hour} 1 * *"
39
+ raise ScheduleError(f"--every must be day, week or month, not '{every}'")
40
+
41
+
42
+ def check_cron(cron: str) -> str:
43
+ """A five-field cron line, as GitHub accepts it."""
44
+ fields = cron.split()
45
+ if len(fields) != 5 or not all(re.fullmatch(r"[\d*/,\-]+", f) for f in fields):
46
+ raise ScheduleError(f"--cron must have 5 fields like '0 6 * * 1', not '{cron}'")
47
+ return " ".join(fields)
48
+
49
+
50
+ def describe(cron: str) -> str:
51
+ minute, hour, dom, _, dow = cron.split()
52
+ if not (minute.isdigit() and hour.isdigit()):
53
+ return f"on the cron schedule '{cron}' (UTC)"
54
+ at = f"{int(hour):02d}:{int(minute):02d} UTC"
55
+ if dom == "*" and dow == "*":
56
+ return f"every day at {at}"
57
+ if dom == "*" and dow.isdigit() and int(dow) < 7:
58
+ names = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
59
+ return f"every {names[int(dow)]} at {at}"
60
+ if dom == "1" and dow == "*":
61
+ return f"on the 1st of every month at {at}"
62
+ return f"on the cron schedule '{cron}' (UTC)"
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class Target:
67
+ repo_root: Path
68
+ project_rel: str
69
+ """The project folder relative to the repo root ('' for the root)."""
70
+
71
+ @property
72
+ def workflow(self) -> Path:
73
+ slug = re.sub(r"[^A-Za-z0-9]+", "-", self.project_rel).strip("-").lower()
74
+ name = f"patchloop-{slug}.yml" if slug else "patchloop.yml"
75
+ return self.repo_root / ".github" / "workflows" / name
76
+
77
+
78
+ def find_target(project: Path) -> Target:
79
+ top = proc.run(["git", "rev-parse", "--show-toplevel"], cwd=project, timeout=10)
80
+ if not top.ok:
81
+ raise ScheduleError(f"{project} is not inside a git repository")
82
+ root = Path(top.stdout.strip()).resolve()
83
+ rel = project.resolve().relative_to(root)
84
+ return Target(root, "" if rel == Path() else rel.as_posix())
85
+
86
+
87
+ def _quote(value: str) -> str:
88
+ return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
89
+
90
+
91
+ def workflow_text(cron: str, project_rel: str = "", min_severity: str | None = None) -> str:
92
+ name = f"PatchLoop ({project_rel})" if project_rel else "PatchLoop"
93
+ inputs = []
94
+ if project_rel:
95
+ inputs.append(f" path: {_quote(project_rel)}")
96
+ if min_severity:
97
+ inputs.append(f" min-severity: {min_severity.upper()}")
98
+ with_block = ("\n with:\n" + "\n".join(inputs)) if inputs else ""
99
+ return f"""# Written by `patchloop schedule`. Runs PatchLoop {describe(cron)}
100
+ # on GitHub's servers; it opens one PR with the fixes, or updates the open one.
101
+ name: {_quote(name)}
102
+
103
+ on:
104
+ schedule:
105
+ - cron: "{cron}"
106
+ workflow_dispatch: # a "Run workflow" button on the Actions tab
107
+
108
+ permissions:
109
+ contents: write
110
+ pull-requests: write
111
+
112
+ jobs:
113
+ fix:
114
+ runs-on: ubuntu-latest
115
+ steps:
116
+ - uses: actions/checkout@v7
117
+ with:
118
+ fetch-depth: 0
119
+ - uses: {ACTION}{with_block}
120
+ """
121
+
122
+
123
+ def write_workflow(target: Target, text: str, force: bool = False) -> Path:
124
+ path = target.workflow
125
+ if path.exists() and not force:
126
+ raise ScheduleError(f"{path} already exists; use --force to replace it")
127
+ path.parent.mkdir(parents=True, exist_ok=True)
128
+ path.write_text(text, encoding="utf-8")
129
+ return path
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: patchloop
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Fix vulnerable dependencies in Python and JavaScript projects: upgrade, test, rescan, one PR.
5
5
  Keywords: security,vulnerabilities,cve,dependencies,uv,poetry,npm,pnpm,yarn
6
6
  Author: Ayush Kumar Singh
@@ -317,6 +317,66 @@ Poetry 1.x and 2.x both work.
317
317
  Poetry rejects any version that declares `python <4` when the project's range is open-ended
318
318
  (`>=3.12`), so bound it (`>=3.12,<4` or `^3.12`), as most Poetry projects already do.
319
319
 
320
+ ## Run it on a schedule (GitHub Action)
321
+
322
+ GitHub can run PatchLoop on a schedule on its own servers (your computer can be off). Each
323
+ run opens one PR, or updates the open one. The quickest way to set it up:
324
+
325
+ ```sh
326
+ patchloop schedule # every Monday at 06:00 UTC
327
+ patchloop schedule --every day --at 22:00 # or --every week --day fri, --every month
328
+ patchloop schedule apps/web --cron "0 6 * * 1-5" # a project in a subfolder, any cron line
329
+ ```
330
+
331
+ It writes `.github/workflows/patchloop.yml` (or `patchloop-<folder>.yml`) and prints the
332
+ next steps: commit and push the file, and allow Actions to open PRs (below). The file it
333
+ writes looks like this, if you'd rather write it yourself:
334
+
335
+ ```yaml
336
+ name: PatchLoop
337
+ on:
338
+ schedule:
339
+ - cron: "0 6 * * 1" # every Monday 06:00 UTC; pick any schedule
340
+ workflow_dispatch: # adds a "Run workflow" button
341
+
342
+ permissions:
343
+ contents: write
344
+ pull-requests: write
345
+
346
+ jobs:
347
+ fix:
348
+ runs-on: ubuntu-latest
349
+ steps:
350
+ - uses: actions/checkout@v7
351
+ with:
352
+ fetch-depth: 0
353
+ - uses: AyushSingh012/PatchLoop@v0
354
+ ```
355
+
356
+ One-time repo setting: **Settings → Actions → General → Workflow permissions → "Allow
357
+ GitHub Actions to create and approve pull requests"**. Without it GitHub refuses the PR.
358
+
359
+ Inputs (all optional):
360
+
361
+ | Input | Default | What it does |
362
+ |---|---|---|
363
+ | `command` | `fix` | `fix` opens or updates the PR; `scan` only reports |
364
+ | `path` | `.` | the project folder (for a repo with several projects, one job each) |
365
+ | `min-severity` | from patchloop.yml, else `HIGH` | `LOW`, `MEDIUM`, `HIGH` or `CRITICAL` |
366
+ | `args` | | extra arguments, e.g. `--sarif patchloop.sarif` |
367
+ | `version` | newest | PatchLoop version from PyPI |
368
+ | `token` | `GITHUB_TOKEN` | see below |
369
+ | `fail-on-findings` | `false` | fail the job when vulnerabilities remain |
370
+
371
+ The job installs PatchLoop, osv-scanner, and Poetry or pnpm/yarn when the project needs
372
+ them; uv, Node and git are already on GitHub's runners. Your tests run as usual
373
+ (`validation.test` in patchloop.yml sets the command).
374
+
375
+ PRs opened with the default `GITHUB_TOKEN` don't start your other workflows (GitHub's
376
+ rule), so CI won't run on the PR by itself. To get CI on it, pass a personal access token
377
+ or a GitHub App token with `contents` and `pull-requests` write access:
378
+ `token: ${{ secrets.PATCHLOOP_TOKEN }}`.
379
+
320
380
  ## Output files
321
381
 
322
382
  `scan` and `fix` take `--json FILE` and `--sarif FILE`. The SARIF file (2.1.0) points each
@@ -351,8 +411,8 @@ the CLI writes to `--json`. Nothing is printed.
351
411
  when that fails). Public packages served through a private mirror work; packages that
352
412
  exist only in a private registry have no public advisories, so they are not checked.
353
413
  - Poetry has no workspaces, so a Poetry monorepo is fixed one project folder at a time.
354
- - GitHub only. There is no built-in schedule: run it from a scheduled CI job or cron
355
- (re-runs update the one open PR instead of opening another).
414
+ - GitHub only. Scheduling comes from GitHub Actions (above) or cron; re-runs update the
415
+ one open PR instead of opening another.
356
416
 
357
417
  ## Releasing
358
418
 
@@ -2,7 +2,7 @@ patchloop/__init__.py,sha256=skVZghYJ0bFTzRwyCjjy1CLzQmFc5OPbSZtc4dACiJQ,806
2
2
  patchloop/api.py,sha256=6uN9gTJccm8Q3MfKWmhHmDqH16qcVfQ4ZOK_NVfC79Q,3704
3
3
  patchloop/build.py,sha256=1BGabcRIEN_wCvxNWGrbjxJItyqFCIK1r6Mtkx3sTrs,4288
4
4
  patchloop/classify.py,sha256=s2Py6nPjp1NIeE6CZVEHCav5TT44TmNZS5BWuPW3mcI,5452
5
- patchloop/cli.py,sha256=vFIwH2ZaAVTvoN8FOiEzkr4-Fvvl2G9JKPS7a3yfUjs,12420
5
+ patchloop/cli.py,sha256=zKQlj1HLmZx14l1SWp0oTDZCH9PA8haU9JiyADbNKlU,15022
6
6
  patchloop/config.py,sha256=BbmqcuqeaeTd6TmOpwry-L9JBfj7XLvifLpSYOQ9OMI,5762
7
7
  patchloop/detect.py,sha256=rmzG_8Yo9xNPU9DEQK9UXHusTfKqNkadVXNwu5EhIuw,4531
8
8
  patchloop/doctor.py,sha256=ZfB5GlNlakj_9Qxnri2_PAW_1aEQsterJ881QGziYUE,7028
@@ -15,7 +15,7 @@ patchloop/fixers/js_fix.py,sha256=b46RENe2ornUuJSc55QDDZqtdpZ6fZ2z2LbCZRjpApY,12
15
15
  patchloop/fixers/poetry_fix.py,sha256=biNzKQNq8JW6UKPI7-QTwGONXn01v9vumldpQ1G4des,6243
16
16
  patchloop/fixers/uv_fix.py,sha256=sAMqcH1wyqH52QtEF23M7YYx-FJubJNT1T8ihGs-zcU,4766
17
17
  patchloop/git_ops.py,sha256=WUaROKeEz_f1HvFv_TtIT_YB7utN9N04i_uTqPn9gaU,6833
18
- patchloop/github.py,sha256=iN3thq8AU5QN9ei3H6UueOR4MDmmCI6Pd9x1kLxjP8M,6373
18
+ patchloop/github.py,sha256=wxi6qTSem6EuoCbCQ9xGYXPuBj-leeDxXXs6mO7sE6c,6555
19
19
  patchloop/hints.py,sha256=WYsYoiUPzIAJVPECW8QFn_J1GEQG33BJVNuDoZr9cGs,6418
20
20
  patchloop/images.py,sha256=BreHOE1-11W91zchle6hxoATDsR0f20lf_GJ4B5Nlpk,7828
21
21
  patchloop/isolate.py,sha256=DNSWHeW7D9zXVXUWpNxLElN4faSS9CPKLABuQykdMaQ,2029
@@ -39,6 +39,7 @@ patchloop/report/json_out.py,sha256=6z3tRnvFDKNt0TwYS5rpH3Ruf7NO8ctMIPxldJhAwkw,
39
39
  patchloop/report/sarif.py,sha256=SyJTH_dugDKqjn8lRES-_hcLD4Q_SYDbBSNCJiMEZu8,5157
40
40
  patchloop/runner.py,sha256=nS671LB_40eZh4ZG8U9ShVjdmCQwNVSQCVoiT1p7D7E,18509
41
41
  patchloop/scanner.py,sha256=lZiF59YV_Jl9Uo8DIkDNC-P-HDvtx4bgZTSJ-wrPS1U,7688
42
+ patchloop/schedule.py,sha256=kNR83roWsXdU52k3XSwmmMwUhy-xubi58-iF-sRaLF4,4571
42
43
  patchloop/sources/__init__.py,sha256=MXngt1WOxfGlCcBw2xijvaNjTI96v8V709kwqWUiqxA,70
43
44
  patchloop/sources/base.py,sha256=Dup3r3fsaF5mLyC5avQYNtN8Qg-6q3iGUCJpLzWWJVI,136
44
45
  patchloop/sources/imports.py,sha256=Y9NKyBz5dNRSJF8yenHkAw2x1M3ub1tjlqgFFFeGaGI,10720
@@ -49,8 +50,8 @@ patchloop/validate.py,sha256=jHgjKRgwNXFWSGeKHwUmtnm9q3AAcoLp69ryIAao7zI,7853
49
50
  patchloop/versions.py,sha256=w1RLRVX3qPWMe6KeBDWmikEZTRfDPKH23NcVxu_uZ2k,2567
50
51
  patchloop/workspaces.py,sha256=DDVR_Yxpx-DQqwkRjJKvFBADYo9AjGVdQNZ-zFVeyLg,5502
51
52
  patchloop/worktree.py,sha256=Nhrg6mXJJdAkCpItykbGHZ62l0x_1svVlWB15EzbGMY,5653
52
- patchloop-0.2.0.dist-info/licenses/LICENSE,sha256=b9nK3LhprXJT-KtmuZJIuDeFdNy7Hq0FR-R_f2oAer4,1074
53
- patchloop-0.2.0.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
54
- patchloop-0.2.0.dist-info/entry_points.txt,sha256=6Rzny6Msr-FRkBmtG1Wwi3vN2BCnhyovObirG5MAFhI,49
55
- patchloop-0.2.0.dist-info/METADATA,sha256=DUCIA7Px8lmRmbb1kXquDbn8cG7S6NvVo1FMSwTUAqI,18296
56
- patchloop-0.2.0.dist-info/RECORD,,
53
+ patchloop-0.3.0.dist-info/licenses/LICENSE,sha256=b9nK3LhprXJT-KtmuZJIuDeFdNy7Hq0FR-R_f2oAer4,1074
54
+ patchloop-0.3.0.dist-info/WHEEL,sha256=wfHFB5CQ4yOA68LQ_ISeFjKJGxj2GfVzMH9QxkYgrCw,81
55
+ patchloop-0.3.0.dist-info/entry_points.txt,sha256=6Rzny6Msr-FRkBmtG1Wwi3vN2BCnhyovObirG5MAFhI,49
56
+ patchloop-0.3.0.dist-info/METADATA,sha256=6KlaJgtUGX4hTZpUgHLBembUjKTDqUS2E8JAV0kpBEY,20660
57
+ patchloop-0.3.0.dist-info/RECORD,,