-
Notifications
You must be signed in to change notification settings - Fork 54
Add inline-script cache key hash utility (PEP 723 PR 1/16) #1634
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
StellaHuang95
wants to merge
2
commits into
microsoft:main
Choose a base branch
from
StellaHuang95:pep723-pr1-cache-hash
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+415
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| import { createHash } from 'crypto'; | ||
| import { normalizePackageName } from '../managers/builtin/utils'; | ||
| import { normalizePath } from './utils/pathUtils'; | ||
|
|
||
| /** Length, in hex chars, of the cache key returned by {@link computeCacheKey}. 16 = 64 bits of SHA-256; fixed-length and filesystem-safe. */ | ||
| export const CACHE_KEY_HEX_LENGTH = 16; | ||
|
|
||
| /** | ||
| * Inputs that participate in the cache key. | ||
| * | ||
| * **Caller contract**: `interpreterPath` must be an absolute path that the | ||
| * caller has already resolved through symlinks (e.g. via `fs.realpath()`). | ||
| * This function does no I/O. Two string-distinct paths that point to the | ||
| * same physical executable will produce two different cache keys. | ||
| */ | ||
| export interface CacheKeyInputs { | ||
| readonly dependencies: readonly string[]; | ||
| readonly interpreterPath: string; | ||
| } | ||
|
|
||
| function normalizeExtras(inner: string): string { | ||
| const items = inner | ||
| .split(',') | ||
| .map((e) => e.trim()) | ||
| .filter((e) => e.length > 0) | ||
| .map((e) => normalizePackageName(e)); | ||
| const deduped = Array.from(new Set(items)).sort(); | ||
| return deduped.length > 0 ? `[${deduped.join(',')}]` : ''; | ||
| } | ||
|
|
||
| /** | ||
| * Canonicalize a PEP 723 dependency entry so common variants of the same | ||
| * requirement produce identical strings. Not a full PEP 508 parser — only | ||
| * folds the superficial edits users are likely to make: | ||
| * | ||
| * "Requests" → "requests" | ||
| * "Flask-Login" → "flask-login" | ||
| * "requests <3" → "requests<3" | ||
| * "requests <3, !=2.0" → "requests<3,!=2.0" | ||
| * "Requests[Security,Socks]" → "requests[security,socks]" | ||
| * "requests[socks,security]" → "requests[security,socks]" | ||
| * "requests[security,Security]" → "requests[security]" | ||
| * | ||
| * Extras (per PEP 503) are lowercased, separator-folded ([._-]+ → -), | ||
| * deduplicated, and sorted alphabetically — same canonical form pip and | ||
| * uv use for the project name, applied to each extra. | ||
| */ | ||
| export function normalizeDependency(dep: string): string { | ||
| const trimmed = dep.trim(); | ||
| if (trimmed.length === 0) { | ||
| return ''; | ||
| } | ||
|
|
||
| const nameMatch = trimmed.match(/^[A-Za-z0-9_.-]+/); | ||
| if (!nameMatch) { | ||
| // URL/VCS spec or other malformed entry — return trimmed so the | ||
| // hash stays deterministic without pretending to parse it. | ||
| return trimmed; | ||
| } | ||
| const name = normalizePackageName(nameMatch[0]); | ||
| let rest = trimmed.slice(nameMatch[0].length); | ||
|
|
||
| let extras = ''; | ||
| const extrasMatch = rest.match(/^\s*\[([^\]]*)\]/); | ||
| if (extrasMatch) { | ||
| extras = normalizeExtras(extrasMatch[1]); | ||
| rest = rest.slice(extrasMatch[0].length); | ||
| } | ||
|
|
||
| const compactedRest = rest | ||
| .replace(/\s+/g, ' ') | ||
| .replace(/\s*([<>=!~]=?)\s*/g, '$1') | ||
| .trim(); | ||
|
|
||
| return `${name}${extras}${compactedRest}`; | ||
| } | ||
|
|
||
| export function normalizeInterpreterPath(interpreterPath: string): string { | ||
| return normalizePath(interpreterPath); | ||
| } | ||
|
|
||
| /** | ||
| * Compute the deterministic cache key for an inline-script env. The | ||
| * payload uses a versioned, labelled-line shape — any future hashed input | ||
| * MUST extend this shape rather than appending a new separator, or | ||
| * existing hashes break silently. | ||
| */ | ||
| export function computeCacheKey(inputs: CacheKeyInputs): string { | ||
| const normalizedDeps = Array.from( | ||
| new Set(inputs.dependencies.map((d) => normalizeDependency(d)).filter((d) => d.length > 0)), | ||
| ).sort(); | ||
| const normalizedInterpreter = normalizeInterpreterPath(inputs.interpreterPath); | ||
|
|
||
| const payload = ['v1', `interpreter=${normalizedInterpreter}`, `deps=${normalizedDeps.join('\n ')}`].join('\n'); | ||
|
|
||
| return createHash('sha256').update(payload, 'utf8').digest('hex').slice(0, CACHE_KEY_HEX_LENGTH); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
wondering if all of these should live in a PEP 508 file so ai can more easily find and re-use these helpers at other points
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes it makes sense to move the normalizePEP503Name to a util file for common use, I will do that. But I would keep the remaining dependency canonicalization there because it intentionally implements only cache-equivalent transformations, not full PEP 508 parsing, treating it as reuseable could lead to incorrect use.