Change Prettier settings (#36)

## Summary

I know this is a little tedious but I'd prefer to use the same settings
as in Ruff.
This commit is contained in:
Charlie Marsh 2024-09-05 08:06:45 -04:00 committed by GitHub
parent 1785c7bde0
commit 182c9c7e92
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
32 changed files with 5536 additions and 5497 deletions

20
.editorconfig Normal file
View File

@ -0,0 +1,20 @@
# Check http://editorconfig.org for more information
# This is the main config file for this project:
root = true
[*]
charset = utf-8
trim_trailing_whitespace = true
end_of_line = lf
indent_style = space
insert_final_newline = true
indent_size = 2
[*.{rs,py,pyi}]
indent_size = 4
[*.snap]
trim_trailing_whitespace = false
[*.md]
max_line_length = 100

View File

@ -17,7 +17,7 @@
"@typescript-eslint/no-unused-vars": "error",
"@typescript-eslint/explicit-member-accessibility": [
"error",
{"accessibility": "no-public"}
{ "accessibility": "no-public" }
],
"@typescript-eslint/no-require-imports": "error",
"@typescript-eslint/array-type": "error",
@ -27,7 +27,7 @@
"@typescript-eslint/consistent-type-assertions": "error",
"@typescript-eslint/explicit-function-return-type": [
"error",
{"allowExpressions": true}
{ "allowExpressions": true }
],
"@typescript-eslint/func-call-spacing": ["error", "never"],
"@typescript-eslint/no-array-constructor": "error",
@ -50,8 +50,6 @@
"@typescript-eslint/promise-function-async": "error",
"@typescript-eslint/require-array-sort-compare": "error",
"@typescript-eslint/restrict-plus-operands": "error",
"semi": "off",
"@typescript-eslint/semi": ["error", "never"],
"@typescript-eslint/type-annotation-spacing": "error",
"@typescript-eslint/unbound-method": "error"
},

2
.gitattributes vendored
View File

@ -1,2 +1,2 @@
* text=auto eol=lf
dist/** -diff linguist-generated=true
dist/** -diff linguist-generated=true

View File

@ -1,48 +1,48 @@
name-template: 'v$RESOLVED_VERSION 🌈'
tag-template: 'v$RESOLVED_VERSION'
name-template: "v$RESOLVED_VERSION 🌈"
tag-template: "v$RESOLVED_VERSION"
categories:
- title: '🚨 Breaking changes'
- title: "🚨 Breaking changes"
labels:
- 'breaking-change'
- title: '✨ New features'
- "breaking-change"
- title: "✨ New features"
labels:
- 'new-feature'
- title: '🐛 Bug fixes'
- "new-feature"
- title: "🐛 Bug fixes"
labels:
- 'bugfix'
- title: '🚀 Enhancements'
- "bugfix"
- title: "🚀 Enhancements"
labels:
- 'enhancement'
- 'refactor'
- 'performance'
- title: '🧰 Maintenance'
- "enhancement"
- "refactor"
- "performance"
- title: "🧰 Maintenance"
labels:
- 'maintenance'
- 'ci'
- 'default-version-update'
- title: '📚 Documentation'
- "maintenance"
- "ci"
- "default-version-update"
- title: "📚 Documentation"
labels:
- 'documentation'
- title: '⬆️ Dependency updates'
- "documentation"
- title: "⬆️ Dependency updates"
labels:
- 'dependencies'
change-template: '- $TITLE @$AUTHOR (#$NUMBER)'
- "dependencies"
change-template: "- $TITLE @$AUTHOR (#$NUMBER)"
change-title-escapes: '\<*_&' # You can add # and @ to disable mentions, and add ` to disable code blocks.
version-resolver:
major:
labels:
- 'major'
- 'breaking-change'
- "major"
- "breaking-change"
minor:
labels:
- 'minor'
- 'new-feature'
- 'enhancement'
- "minor"
- "new-feature"
- "enhancement"
patch:
labels:
- 'patch'
- 'bugfix'
- 'default-version-update'
- "patch"
- "bugfix"
- "default-version-update"
default: patch
template: |
## Changes

View File

@ -10,10 +10,10 @@ on:
branches:
- main
paths-ignore:
- '**.md'
- "**.md"
pull_request:
paths-ignore:
- '**.md'
- "**.md"
workflow_dispatch:
jobs:

View File

@ -9,7 +9,7 @@
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: 'CodeQL'
name: "CodeQL"
on:
push:
@ -18,7 +18,7 @@ on:
# The branches below must be a subset of the branches above
branches: [main]
schedule:
- cron: '31 7 * * 3'
- cron: "31 7 * * 3"
jobs:
analyze:
@ -32,7 +32,7 @@ jobs:
strategy:
fail-fast: false
matrix:
language: ['TypeScript']
language: ["TypeScript"]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support

View File

@ -1,4 +1,4 @@
name: 'test-cache-windows'
name: "test-cache-windows"
on:
pull_request:
push:

View File

@ -1,4 +1,4 @@
name: 'test-cache'
name: "test-cache"
on:
pull_request:
push:

View File

@ -1,4 +1,4 @@
name: 'test-windows'
name: "test-windows"
on:
pull_request:
push:

View File

@ -1,4 +1,4 @@
name: 'test'
name: "test"
on:
pull_request:
push:
@ -19,7 +19,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
node-version: "20"
- run: |
npm install
- run: |
@ -42,7 +42,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest, macos-14, oracle-aarch64]
uv-version: ['latest', '0.3.0', '0.3.2']
uv-version: ["latest", "0.3.0", "0.3.2"]
steps:
- uses: actions/checkout@v4
- name: Install version ${{ matrix.uv-version }}
@ -58,19 +58,19 @@ jobs:
matrix:
os: [ubuntu-latest, oracle-aarch64]
checksum:
['4d9279ad5ca596b1e2d703901d508430eb07564dc4d8837de9e2fca9c90f8ecd']
["4d9279ad5ca596b1e2d703901d508430eb07564dc4d8837de9e2fca9c90f8ecd"]
exclude:
- os: oracle-aarch64
checksum: '4d9279ad5ca596b1e2d703901d508430eb07564dc4d8837de9e2fca9c90f8ecd'
checksum: "4d9279ad5ca596b1e2d703901d508430eb07564dc4d8837de9e2fca9c90f8ecd"
include:
- os: oracle-aarch64
checksum: 'e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8'
checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8"
steps:
- uses: actions/checkout@v4
- name: Checksum matches expected
uses: ./
with:
version: '0.3.2'
version: "0.3.2"
checksum: ${{ matrix.checksum }}
github-token: ${{ secrets.GITHUB_TOKEN }}
test-without-github-token:

View File

@ -1,4 +1,4 @@
name: 'Update default version and checksums'
name: "Update default version and checksums"
on:
workflow_dispatch:
@ -9,7 +9,7 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
node-version: "20"
- name: Update default version and checksums
id: update-default-version
run:
@ -20,14 +20,14 @@ jobs:
- name: Create Pull Request
uses: peter-evans/create-pull-request@4320041ed380b20e97d388d56a7fb4f9b8c20e79 # v7.0.0
with:
commit-message: 'chore: update checksums'
commit-message: "chore: update checksums"
title:
'chore: update default version to ${{
steps.update-default-version.outputs.latest-version }}'
"chore: update default version to ${{
steps.update-default-version.outputs.latest-version }}"
body:
'chore: update default version to ${{
steps.update-default-version.outputs.latest-version }}'
"chore: update default version to ${{
steps.update-default-version.outputs.latest-version }}"
base: main
labels: 'automated-pr,default-version-update'
labels: "automated-pr,default-version-update"
branch: update-default-version-pr
delete-branch: true

View File

@ -5,9 +5,9 @@ name: Update Major Minor Tags
on:
push:
branches-ignore:
- '**'
- "**"
tags:
- 'v*.*.*'
- "v*.*.*"
jobs:
update_major_minor_tags:

View File

@ -1,11 +1,4 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": false,
"singleQuote": true,
"trailingComma": "none",
"bracketSpacing": false,
"arrowParens": "avoid",
"trailingComma": "all",
"proseWrap": "always"
}

View File

@ -23,7 +23,8 @@ Set up your GitHub Actions workflow with a specific version of [uv](https://docs
## Usage
Example workflow in a real world project can be found [here](https://github.com/eifinger/hass-weenect/blob/main/.github/workflows/ci.yml)
Example workflow in a real world project can be found
[here](https://github.com/eifinger/hass-weenect/blob/main/.github/workflows/ci.yml)
### Install specific version
@ -33,47 +34,46 @@ You can also specify a specific version of uv
- name: Install a specific version
uses: astral-sh/setup-uv@v1
with:
version: '0.4.4'
version: "0.4.4"
```
### Install latest version
By default this action installs the version defined as `default` in `action.yml`.
This gets automatically updated in a new release of this action when a new version of uv is released.
If you don't want to wait for a new release of this action you can use `version: latest`.
By default this action installs the version defined as `default` in `action.yml`. This gets
automatically updated in a new release of this action when a new version of uv is released. If you
don't want to wait for a new release of this action you can use `version: latest`.
> [!WARNING]
> Using the `latest` version means that the uv executable gets downloaded every single time instead of loaded from the tools cache.
> This can take up to 20s depending on the download speed.
> This does not affect the uv cache.
> Using the `latest` version means that the uv executable gets downloaded every single time instead
> of loaded from the tools cache. This can take up to 20s depending on the download speed. This does
> not affect the uv cache.
```yaml
- name: Install a specific version
uses: astral-sh/setup-uv@v1
with:
version: 'latest'
version: "latest"
```
### Validate checksum
You can also specify a checksum to validate the downloaded file.
Checksums up to the default version are automatically verified by this action.
The sha265 hashes can be found on the [releases page](https://github.com/astral-sh/uv/releases)
of the uv repo.
You can also specify a checksum to validate the downloaded file. Checksums up to the default version
are automatically verified by this action. The sha265 hashes can be found on the
[releases page](https://github.com/astral-sh/uv/releases) of the uv repo.
```yaml
- name: Install a specific version and validate the checksum
uses: astral-sh/setup-uv@v1
with:
version: '0.3.1'
checksum: 'e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8'
version: "0.3.1"
checksum: "e11b01402ab645392c7ad6044db63d37e4fd1e745e015306993b07695ea5f9f8"
```
### Enable caching
If you enable caching the [uv cache](https://docs.astral.sh/uv/concepts/cache/) will
be cached to the GitHub Actions Cache. This can speed up runs which can reuse the cache
by several minutes. The cache will always be reused on self-hosted runners.
If you enable caching the [uv cache](https://docs.astral.sh/uv/concepts/cache/) will be cached to
the GitHub Actions Cache. This can speed up runs which can reuse the cache by several minutes. The
cache will always be reused on self-hosted runners.
You can optionally define a custom cache key suffix.
@ -83,11 +83,11 @@ You can optionally define a custom cache key suffix.
uses: astral-sh/setup-uv@v1
with:
enable-cache: true
cache-suffix: 'optional-suffix'
cache-suffix: "optional-suffix"
```
When the cache was successfully restored the output `cache-hit` will be set to `true` and you can use it in subsequent steps.
For the example above you can use it like this:
When the cache was successfully restored the output `cache-hit` will be set to `true` and you can
use it in subsequent steps. For the example above you can use it like this:
```yaml
- name: Do something if the cache was restored
@ -105,21 +105,21 @@ you can specify the path with the `cache-local-path` input.
uses: astral-sh/setup-uv@v1
with:
enable-cache: true
cache-local-path: '/path/to/cache'
cache-local-path: "/path/to/cache"
```
#### Cache dependency glob
If you want to control when the cache is invalidated you can specify a glob pattern with the `cache-dependency-glob` input.
The cache will be invalidated if any file matching the glob pattern changes.
The glob matches files relative to the repository root.
If you want to control when the cache is invalidated you can specify a glob pattern with the
`cache-dependency-glob` input. The cache will be invalidated if any file matching the glob pattern
changes. The glob matches files relative to the repository root.
```yaml
- name: Define a cache dependency glob
uses: astral-sh/setup-uv@v1
with:
enable-cache: true
cache-dependency-glob: 'uv.lock'
cache-dependency-glob: "uv.lock"
```
```yaml
@ -127,12 +127,13 @@ The glob matches files relative to the repository root.
uses: astral-sh/setup-uv@v1
with:
enable-cache: true
cache-dependency-glob: '**requirements*.txt'
cache-dependency-glob: "**requirements*.txt"
```
### API rate limit
To avoid hitting the error `API rate limit exceeded` you can supply a GitHub token with the `github-token` input.
To avoid hitting the error `API rate limit exceeded` you can supply a GitHub token with the
`github-token` input.
```yaml
- name: Install uv and supply a GitHub token
@ -143,9 +144,12 @@ To avoid hitting the error `API rate limit exceeded` you can supply a GitHub tok
## How it works
This action downloads uv from the releases of the [uv repo](https://github.com/astral-sh/uv) and uses the [GitHub Actions Toolkit](https://github.com/actions/toolkit) to cache it as a tool to speed up consecutive runs on self-hosted runners.
This action downloads uv from the releases of the [uv repo](https://github.com/astral-sh/uv) and
uses the [GitHub Actions Toolkit](https://github.com/actions/toolkit) to cache it as a tool to speed
up consecutive runs on self-hosted runners.
The installed version of uv is then added to the runner path so other steps can just use it by calling `uv`.
The installed version of uv is then added to the runner path so other steps can just use it by
calling `uv`.
## FAQ
@ -166,7 +170,8 @@ A simple example workflow could look like this:
run: uv run --frozen pytest
```
If you want to have a specific python version installed you can use the command [`uv python install`](https://docs.astral.sh/uv/guides/install-python/):
If you want to have a specific python version installed you can use the command
[`uv python install`](https://docs.astral.sh/uv/guides/install-python/):
```yaml
- name: Install the latest version of uv
@ -179,10 +184,12 @@ If you want to have a specific python version installed you can use the command
### What is the default version?
By default, this action installs the version defined as `default` in `action.yml`.
When a new release of uv is published this triggers an automatic release of this action with the new version as `default`.
By default, this action installs the version defined as `default` in `action.yml`. When a new
release of uv is published this triggers an automatic release of this action with the new version as
`default`.
If you have to know the version installed for other steps of your workflow you can use the `uv-version` output:
If you have to know the version installed for other steps of your workflow you can use the
`uv-version` output:
```yaml
- name: Checkout the repository
@ -197,8 +204,9 @@ If you have to know the version installed for other steps of your workflow you c
## Acknowledgements
`setup-uv` was initially written and published by [Kevin Stillhammer](https://github.com/eifinger)
before moving under the official [Astral](https://github.com/astral-sh) GitHub organization. You
can support Kevin's work in open source on [Buy me a coffee](https://www.buymeacoffee.com/eifinger) or [PayPal](https://paypal.me/kevinstillhammer).
before moving under the official [Astral](https://github.com/astral-sh) GitHub organization. You can
support Kevin's work in open source on [Buy me a coffee](https://www.buymeacoffee.com/eifinger) or
[PayPal](https://paypal.me/kevinstillhammer).
## License

View File

@ -1,37 +1,37 @@
import {expect, test, it} from '@jest/globals'
import { expect, test, it } from "@jest/globals";
import {
isknownVersion,
validateChecksum
} from '../../../src/download/checksum/checksum'
validateChecksum,
} from "../../../src/download/checksum/checksum";
test('checksum should match', async () => {
test("checksum should match", async () => {
const validChecksum =
'f3da96ec7e995debee7f5d52ecd034dfb7074309a1da42f76429ecb814d813a3'
const filePath = '__tests__/fixtures/checksumfile'
"f3da96ec7e995debee7f5d52ecd034dfb7074309a1da42f76429ecb814d813a3";
const filePath = "__tests__/fixtures/checksumfile";
// string params don't matter only test the checksum mechanism, not known checksums
await validateChecksum(
validChecksum,
filePath,
'aarch64',
'pc-windows-msvc',
'1.2.3'
)
})
"aarch64",
"pc-windows-msvc",
"1.2.3",
);
});
type KnownVersionFixture = {version: string; known: boolean}
type KnownVersionFixture = { version: string; known: boolean };
it.each<KnownVersionFixture>([
{
version: '0.3.0',
known: true
version: "0.3.0",
known: true,
},
{
version: '0.0.15',
known: false
}
version: "0.0.15",
known: false,
},
])(
'isknownVersion should return $known for version $version',
({version, known}) => {
expect(isknownVersion(version)).toBe(known)
}
)
"isknownVersion should return $known for version $version",
({ version, known }) => {
expect(isknownVersion(version)).toBe(known);
},
);

View File

@ -1,42 +1,42 @@
name: 'Python setup uv'
description: 'Set up your GitHub Actions workflow with a specific version of uv'
author: 'eifinger'
name: "Python setup uv"
description: "Set up your GitHub Actions workflow with a specific version of uv"
author: "eifinger"
inputs:
version:
description: 'The version of uv to install'
default: '0.4.4'
description: "The version of uv to install"
default: "0.4.4"
checksum:
description: 'The checksum of the uv version to install'
description: "The checksum of the uv version to install"
required: false
github-token:
description:
'Used to increase the rate limit when retrieving versions and downloading
uv.'
"Used to increase the rate limit when retrieving versions and downloading
uv."
required: false
enable-cache:
description: 'Enable caching of the uv cache'
default: 'false'
description: "Enable caching of the uv cache"
default: "false"
cache-dependency-glob:
description:
'Glob pattern to match files relative to the repository root to control
the cache. e.g. "uv.lock"'
required: false
cache-suffix:
description: 'Suffix for the cache key'
description: "Suffix for the cache key"
required: false
cache-local-path:
description: 'Local path to store the cache.'
default: '/tmp/setup-uv-cache'
description: "Local path to store the cache."
default: "/tmp/setup-uv-cache"
outputs:
uv-version:
description: 'The installed uv version. Useful when using latest.'
description: "The installed uv version. Useful when using latest."
cache-hit:
description: 'A boolean value to indicate a cache entry was found'
description: "A boolean value to indicate a cache entry was found"
runs:
using: 'node20'
main: 'dist/setup/index.js'
post: 'dist/save-cache/index.js'
using: "node20"
main: "dist/setup/index.js"
post: "dist/save-cache/index.js"
post-if: success()
branding:
icon: 'package'
color: 'blue'
icon: "package"
color: "blue"

60
dist/save-cache/index.js generated vendored
View File

@ -82795,9 +82795,9 @@ const core = __importStar(__nccwpck_require__(2186));
const path_1 = __importDefault(__nccwpck_require__(1017));
const inputs_1 = __nccwpck_require__(9378);
const platforms_1 = __nccwpck_require__(6005);
exports.STATE_CACHE_KEY = 'cache-key';
exports.STATE_CACHE_MATCHED_KEY = 'cache-matched-key';
const CACHE_VERSION = '1';
exports.STATE_CACHE_KEY = "cache-key";
exports.STATE_CACHE_MATCHED_KEY = "cache-matched-key";
const CACHE_VERSION = "1";
function restoreCache(version) {
return __awaiter(this, void 0, void 0, function* () {
const cacheKey = yield computeKeys(version);
@ -82809,7 +82809,7 @@ function restoreCache(version) {
catch (err) {
const message = err.message;
core.warning(message);
core.setOutput('cache-hit', false);
core.setOutput("cache-hit", false);
return;
}
core.saveState(exports.STATE_CACHE_KEY, cacheKey);
@ -82819,30 +82819,30 @@ function restoreCache(version) {
exports.restoreCache = restoreCache;
function computeKeys(version) {
return __awaiter(this, void 0, void 0, function* () {
let cacheDependencyPathHash = '-';
if (inputs_1.cacheDependencyGlob !== '') {
const fullCacheDependencyGlob = `${process.env['GITHUB_WORKSPACE']}${path_1.default.sep}${inputs_1.cacheDependencyGlob}`;
let cacheDependencyPathHash = "-";
if (inputs_1.cacheDependencyGlob !== "") {
const fullCacheDependencyGlob = `${process.env["GITHUB_WORKSPACE"]}${path_1.default.sep}${inputs_1.cacheDependencyGlob}`;
cacheDependencyPathHash += yield glob.hashFiles(fullCacheDependencyGlob);
if (cacheDependencyPathHash === '-') {
if (cacheDependencyPathHash === "-") {
throw new Error(`No file in ${process.cwd()} matched to [${inputs_1.cacheDependencyGlob}], make sure you have checked out the target repository`);
}
}
else {
cacheDependencyPathHash += 'no-dependency-glob';
cacheDependencyPathHash += "no-dependency-glob";
}
const suffix = inputs_1.cacheSuffix ? `-${inputs_1.cacheSuffix}` : '';
const suffix = inputs_1.cacheSuffix ? `-${inputs_1.cacheSuffix}` : "";
return `setup-uv-${CACHE_VERSION}-${(0, platforms_1.getArch)()}-${(0, platforms_1.getPlatform)()}-${version}${cacheDependencyPathHash}${suffix}`;
});
}
function handleMatchResult(matchedKey, primaryKey) {
if (!matchedKey) {
core.info(`No GitHub Actions cache found for key: ${primaryKey}`);
core.setOutput('cache-hit', false);
core.setOutput("cache-hit", false);
return;
}
core.saveState(exports.STATE_CACHE_MATCHED_KEY, matchedKey);
core.info(`uv cache restored from GitHub Actions cache with key: ${matchedKey}`);
core.setOutput('cache-hit', true);
core.setOutput("cache-hit", true);
}
@ -82912,7 +82912,7 @@ function saveCache() {
const cacheKey = core.getState(restore_cache_1.STATE_CACHE_KEY);
const matchedKey = core.getState(restore_cache_1.STATE_CACHE_MATCHED_KEY);
if (!cacheKey) {
core.warning('Error retrieving cache key from state.');
core.warning("Error retrieving cache key from state.");
return;
}
else if (matchedKey === cacheKey) {
@ -82928,11 +82928,11 @@ function saveCache() {
function pruneCache() {
return __awaiter(this, void 0, void 0, function* () {
const options = {
silent: !core.isDebug()
silent: !core.isDebug(),
};
const execArgs = ['cache', 'prune', '--ci'];
core.info('Pruning cache...');
yield exec.exec('uv', execArgs, options);
const execArgs = ["cache", "prune", "--ci"];
core.info("Pruning cache...");
yield exec.exec("uv", execArgs, options);
});
}
run();
@ -82971,13 +82971,13 @@ var __importStar = (this && this.__importStar) || function (mod) {
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.cacheDependencyGlob = exports.githubToken = exports.cacheLocalPath = exports.cacheSuffix = exports.enableCache = exports.checkSum = exports.version = void 0;
const core = __importStar(__nccwpck_require__(2186));
exports.version = core.getInput('version');
exports.checkSum = core.getInput('checksum');
exports.enableCache = core.getInput('enable-cache') === 'true';
exports.cacheSuffix = core.getInput('cache-suffix') || '';
exports.cacheLocalPath = core.getInput('cache-local-path');
exports.githubToken = core.getInput('github-token');
exports.cacheDependencyGlob = core.getInput('cache-dependency-glob');
exports.version = core.getInput("version");
exports.checkSum = core.getInput("checksum");
exports.enableCache = core.getInput("enable-cache") === "true";
exports.cacheSuffix = core.getInput("cache-suffix") || "";
exports.cacheLocalPath = core.getInput("cache-local-path");
exports.githubToken = core.getInput("github-token");
exports.cacheDependencyGlob = core.getInput("cache-dependency-glob");
/***/ }),
@ -82992,9 +82992,9 @@ exports.getPlatform = exports.getArch = void 0;
function getArch() {
const arch = process.arch;
const archMapping = {
ia32: 'i686',
x64: 'x86_64',
arm64: 'aarch64'
ia32: "i686",
x64: "x86_64",
arm64: "aarch64",
};
if (arch in archMapping) {
return archMapping[arch];
@ -83004,9 +83004,9 @@ exports.getArch = getArch;
function getPlatform() {
const platform = process.platform;
const platformMapping = {
linux: 'unknown-linux-gnu',
darwin: 'apple-darwin',
win32: 'pc-windows-msvc'
linux: "unknown-linux-gnu",
darwin: "apple-darwin",
win32: "pc-windows-msvc",
};
if (platform in platformMapping) {
return platformMapping[platform];

3410
dist/setup/index.js generated vendored

File diff suppressed because it is too large Load Diff

38
dist/update-default-version/index.js generated vendored
View File

@ -32713,34 +32713,34 @@ const tc = __importStar(__nccwpck_require__(7784));
function updateChecksums(filePath, downloadUrls) {
return __awaiter(this, void 0, void 0, function* () {
yield fs_1.promises.rm(filePath);
yield fs_1.promises.appendFile(filePath, '// AUTOGENERATED_DO_NOT_EDIT\nexport const KNOWN_CHECKSUMS: {[key: string]: string} = {\n');
yield fs_1.promises.appendFile(filePath, "// AUTOGENERATED_DO_NOT_EDIT\nexport const KNOWN_CHECKSUMS: {[key: string]: string} = {\n");
let firstLine = true;
for (const downloadUrl of downloadUrls) {
const content = yield downloadAssetContent(downloadUrl);
const checksum = content.split(' ')[0].trim();
const checksum = content.split(" ")[0].trim();
const key = getKey(downloadUrl);
if (!firstLine) {
yield fs_1.promises.appendFile(filePath, ',\n');
yield fs_1.promises.appendFile(filePath, ",\n");
}
yield fs_1.promises.appendFile(filePath, ` '${key}':\n '${checksum}'`);
firstLine = false;
}
yield fs_1.promises.appendFile(filePath, '}\n');
yield fs_1.promises.appendFile(filePath, "}\n");
});
}
exports.updateChecksums = updateChecksums;
function getKey(downloadUrl) {
// https://github.com/astral-sh/uv/releases/download/0.3.2/uv-aarch64-apple-darwin.tar.gz.sha256
const parts = downloadUrl.split('/');
const parts = downloadUrl.split("/");
const fileName = parts[parts.length - 1];
const name = fileName.split('.')[0].split('uv-')[1];
const name = fileName.split(".")[0].split("uv-")[1];
const version = parts[parts.length - 2];
return `${name}-${version}`;
}
function downloadAssetContent(downloadUrl) {
return __awaiter(this, void 0, void 0, function* () {
const downloadPath = yield tc.downloadTool(downloadUrl);
const content = yield fs_1.promises.readFile(downloadPath, 'utf8');
const content = yield fs_1.promises.readFile(downloadPath, "utf8");
return content;
});
}
@ -32808,16 +32808,16 @@ function run() {
const octokit = github.getOctokit(github_token);
const response = yield octokit.paginate(octokit.rest.repos.listReleases, {
owner: utils_1.OWNER,
repo: utils_1.REPO
repo: utils_1.REPO,
});
const downloadUrls = response.flatMap(release => release.assets
.filter(asset => asset.name.endsWith('.sha256'))
.map(asset => asset.browser_download_url));
const downloadUrls = response.flatMap((release) => release.assets
.filter((asset) => asset.name.endsWith(".sha256"))
.map((asset) => asset.browser_download_url));
yield (0, update_known_checksums_1.updateChecksums)(checksumFilePath, downloadUrls);
const latestVersion = response
.map(release => release.tag_name)
.map((release) => release.tag_name)
.sort(semver.rcompare)[0];
core.setOutput('latest-version', latestVersion);
core.setOutput("latest-version", latestVersion);
yield updateDefaultVersion(defaultVersionFilePath, latestVersion);
});
}
@ -32826,7 +32826,7 @@ function updateDefaultVersion(filePath, latestVersion) {
var _a, e_1, _b, _c;
const fileStream = (0, fs_1.createReadStream)(filePath);
const rl = readline.createInterface({
input: fileStream
input: fileStream,
});
let foundDescription = false;
const lines = [];
@ -32839,7 +32839,7 @@ function updateDefaultVersion(filePath, latestVersion) {
line.includes("description: 'The version of uv to install'")) {
foundDescription = true;
}
else if (foundDescription && line.includes('default: ')) {
else if (foundDescription && line.includes("default: ")) {
line = line.replace(/'[^']*'/, `'${latestVersion}'`);
foundDescription = false;
}
@ -32853,7 +32853,7 @@ function updateDefaultVersion(filePath, latestVersion) {
}
finally { if (e_1) throw e_1.error; }
}
yield fs_1.promises.writeFile(filePath, lines.join('\n'));
yield fs_1.promises.writeFile(filePath, lines.join("\n"));
});
}
run();
@ -32868,9 +32868,9 @@ run();
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.TOOL_CACHE_NAME = exports.OWNER = exports.REPO = void 0;
exports.REPO = 'uv';
exports.OWNER = 'astral-sh';
exports.TOOL_CACHE_NAME = 'uv';
exports.REPO = "uv";
exports.OWNER = "astral-sh";
exports.TOOL_CACHE_NAME = "uv";
/***/ }),

View File

@ -1,9 +1,9 @@
module.exports = {
clearMocks: true,
moduleFileExtensions: ['js', 'ts'],
testMatch: ['**/*.test.ts'],
moduleFileExtensions: ["js", "ts"],
testMatch: ["**/*.test.ts"],
transform: {
'^.+\\.ts$': 'ts-jest'
"^.+\\.ts$": "ts-jest",
},
verbose: true
}
verbose: true,
};

View File

@ -1,65 +1,69 @@
import * as cache from '@actions/cache'
import * as glob from '@actions/glob'
import * as core from '@actions/core'
import path from 'path'
import {cacheDependencyGlob, cacheLocalPath, cacheSuffix} from '../utils/inputs'
import {getArch, getPlatform} from '../utils/platforms'
import * as cache from "@actions/cache";
import * as glob from "@actions/glob";
import * as core from "@actions/core";
import path from "path";
import {
cacheDependencyGlob,
cacheLocalPath,
cacheSuffix,
} from "../utils/inputs";
import { getArch, getPlatform } from "../utils/platforms";
export const STATE_CACHE_KEY = 'cache-key'
export const STATE_CACHE_MATCHED_KEY = 'cache-matched-key'
const CACHE_VERSION = '1'
export const STATE_CACHE_KEY = "cache-key";
export const STATE_CACHE_MATCHED_KEY = "cache-matched-key";
const CACHE_VERSION = "1";
export async function restoreCache(version: string): Promise<void> {
const cacheKey = await computeKeys(version)
const cacheKey = await computeKeys(version);
let matchedKey: string | undefined
let matchedKey: string | undefined;
core.info(
`Trying to restore uv cache from GitHub Actions cache with key: ${cacheKey}`
)
`Trying to restore uv cache from GitHub Actions cache with key: ${cacheKey}`,
);
try {
matchedKey = await cache.restoreCache([cacheLocalPath], cacheKey)
matchedKey = await cache.restoreCache([cacheLocalPath], cacheKey);
} catch (err) {
const message = (err as Error).message
core.warning(message)
core.setOutput('cache-hit', false)
return
const message = (err as Error).message;
core.warning(message);
core.setOutput("cache-hit", false);
return;
}
core.saveState(STATE_CACHE_KEY, cacheKey)
core.saveState(STATE_CACHE_KEY, cacheKey);
handleMatchResult(matchedKey, cacheKey)
handleMatchResult(matchedKey, cacheKey);
}
async function computeKeys(version: string): Promise<string> {
let cacheDependencyPathHash = '-'
if (cacheDependencyGlob !== '') {
const fullCacheDependencyGlob = `${process.env['GITHUB_WORKSPACE']}${path.sep}${cacheDependencyGlob}`
cacheDependencyPathHash += await glob.hashFiles(fullCacheDependencyGlob)
if (cacheDependencyPathHash === '-') {
let cacheDependencyPathHash = "-";
if (cacheDependencyGlob !== "") {
const fullCacheDependencyGlob = `${process.env["GITHUB_WORKSPACE"]}${path.sep}${cacheDependencyGlob}`;
cacheDependencyPathHash += await glob.hashFiles(fullCacheDependencyGlob);
if (cacheDependencyPathHash === "-") {
throw new Error(
`No file in ${process.cwd()} matched to [${cacheDependencyGlob}], make sure you have checked out the target repository`
)
`No file in ${process.cwd()} matched to [${cacheDependencyGlob}], make sure you have checked out the target repository`,
);
}
} else {
cacheDependencyPathHash += 'no-dependency-glob'
cacheDependencyPathHash += "no-dependency-glob";
}
const suffix = cacheSuffix ? `-${cacheSuffix}` : ''
return `setup-uv-${CACHE_VERSION}-${getArch()}-${getPlatform()}-${version}${cacheDependencyPathHash}${suffix}`
const suffix = cacheSuffix ? `-${cacheSuffix}` : "";
return `setup-uv-${CACHE_VERSION}-${getArch()}-${getPlatform()}-${version}${cacheDependencyPathHash}${suffix}`;
}
function handleMatchResult(
matchedKey: string | undefined,
primaryKey: string
primaryKey: string,
): void {
if (!matchedKey) {
core.info(`No GitHub Actions cache found for key: ${primaryKey}`)
core.setOutput('cache-hit', false)
return
core.info(`No GitHub Actions cache found for key: ${primaryKey}`);
core.setOutput("cache-hit", false);
return;
}
core.saveState(STATE_CACHE_MATCHED_KEY, matchedKey)
core.saveState(STATE_CACHE_MATCHED_KEY, matchedKey);
core.info(
`uv cache restored from GitHub Actions cache with key: ${matchedKey}`
)
core.setOutput('cache-hit', true)
`uv cache restored from GitHub Actions cache with key: ${matchedKey}`,
);
core.setOutput("cache-hit", true);
}

View File

@ -1,55 +1,55 @@
import * as fs from 'fs'
import * as crypto from 'crypto'
import * as fs from "fs";
import * as crypto from "crypto";
import * as core from '@actions/core'
import {KNOWN_CHECKSUMS} from './known-checksums'
import {Architecture, Platform} from '../../utils/platforms'
import * as core from "@actions/core";
import { KNOWN_CHECKSUMS } from "./known-checksums";
import { Architecture, Platform } from "../../utils/platforms";
export async function validateChecksum(
checkSum: string | undefined,
downloadPath: string,
arch: Architecture,
platform: Platform,
version: string
version: string,
): Promise<void> {
let isValid = true
if (checkSum !== undefined && checkSum !== '') {
isValid = await validateFileCheckSum(downloadPath, checkSum)
let isValid = true;
if (checkSum !== undefined && checkSum !== "") {
isValid = await validateFileCheckSum(downloadPath, checkSum);
} else {
core.debug(`Checksum not provided. Checking known checksums.`)
const key = `${arch}-${platform}-${version}`
core.debug(`Checksum not provided. Checking known checksums.`);
const key = `${arch}-${platform}-${version}`;
if (key in KNOWN_CHECKSUMS) {
const knownChecksum = KNOWN_CHECKSUMS[`${arch}-${platform}-${version}`]
core.debug(`Checking checksum for ${arch}-${platform}-${version}.`)
isValid = await validateFileCheckSum(downloadPath, knownChecksum)
const knownChecksum = KNOWN_CHECKSUMS[`${arch}-${platform}-${version}`];
core.debug(`Checking checksum for ${arch}-${platform}-${version}.`);
isValid = await validateFileCheckSum(downloadPath, knownChecksum);
} else {
core.debug(`No known checksum found for ${key}.`)
core.debug(`No known checksum found for ${key}.`);
}
}
if (!isValid) {
throw new Error(`Checksum for ${downloadPath} did not match ${checkSum}.`)
throw new Error(`Checksum for ${downloadPath} did not match ${checkSum}.`);
}
core.debug(`Checksum for ${downloadPath} is valid.`)
core.debug(`Checksum for ${downloadPath} is valid.`);
}
async function validateFileCheckSum(
filePath: string,
expected: string
expected: string,
): Promise<boolean> {
return new Promise((resolve, reject) => {
const hash = crypto.createHash('sha256')
const stream = fs.createReadStream(filePath)
stream.on('error', err => reject(err))
stream.on('data', chunk => hash.update(chunk))
stream.on('end', () => {
const actual = hash.digest('hex')
resolve(actual === expected)
})
})
const hash = crypto.createHash("sha256");
const stream = fs.createReadStream(filePath);
stream.on("error", (err) => reject(err));
stream.on("data", (chunk) => hash.update(chunk));
stream.on("end", () => {
const actual = hash.digest("hex");
resolve(actual === expected);
});
});
}
export function isknownVersion(version: string): boolean {
const pattern = new RegExp(`^.*-.*-${version}$`)
return Object.keys(KNOWN_CHECKSUMS).some(key => pattern.test(key))
const pattern = new RegExp(`^.*-.*-${version}$`);
return Object.keys(KNOWN_CHECKSUMS).some((key) => pattern.test(key));
}

File diff suppressed because it is too large Load Diff

View File

@ -1,39 +1,39 @@
import {promises as fs} from 'fs'
import * as tc from '@actions/tool-cache'
import { promises as fs } from "fs";
import * as tc from "@actions/tool-cache";
export async function updateChecksums(
filePath: string,
downloadUrls: string[]
downloadUrls: string[],
): Promise<void> {
await fs.rm(filePath)
await fs.rm(filePath);
await fs.appendFile(
filePath,
'// AUTOGENERATED_DO_NOT_EDIT\nexport const KNOWN_CHECKSUMS: {[key: string]: string} = {\n'
)
let firstLine = true
"// AUTOGENERATED_DO_NOT_EDIT\nexport const KNOWN_CHECKSUMS: {[key: string]: string} = {\n",
);
let firstLine = true;
for (const downloadUrl of downloadUrls) {
const content = await downloadAssetContent(downloadUrl)
const checksum = content.split(' ')[0].trim()
const key = getKey(downloadUrl)
const content = await downloadAssetContent(downloadUrl);
const checksum = content.split(" ")[0].trim();
const key = getKey(downloadUrl);
if (!firstLine) {
await fs.appendFile(filePath, ',\n')
await fs.appendFile(filePath, ",\n");
}
await fs.appendFile(filePath, ` '${key}':\n '${checksum}'`)
firstLine = false
await fs.appendFile(filePath, ` '${key}':\n '${checksum}'`);
firstLine = false;
}
await fs.appendFile(filePath, '}\n')
await fs.appendFile(filePath, "}\n");
}
function getKey(downloadUrl: string): string {
// https://github.com/astral-sh/uv/releases/download/0.3.2/uv-aarch64-apple-darwin.tar.gz.sha256
const parts = downloadUrl.split('/')
const fileName = parts[parts.length - 1]
const name = fileName.split('.')[0].split('uv-')[1]
const version = parts[parts.length - 2]
return `${name}-${version}`
const parts = downloadUrl.split("/");
const fileName = parts[parts.length - 1];
const name = fileName.split(".")[0].split("uv-")[1];
const version = parts[parts.length - 2];
return `${name}-${version}`;
}
async function downloadAssetContent(downloadUrl: string): Promise<string> {
const downloadPath = await tc.downloadTool(downloadUrl)
const content = await fs.readFile(downloadPath, 'utf8')
return content
const downloadPath = await tc.downloadTool(downloadUrl);
const content = await fs.readFile(downloadPath, "utf8");
return content;
}

View File

@ -1,47 +1,52 @@
import * as core from '@actions/core'
import * as tc from '@actions/tool-cache'
import * as exec from '@actions/exec'
import * as path from 'path'
import {Architecture, Platform} from '../utils/platforms'
import {validateChecksum} from './checksum/checksum'
import {OWNER, REPO, TOOL_CACHE_NAME} from '../utils/utils'
import * as core from "@actions/core";
import * as tc from "@actions/tool-cache";
import * as exec from "@actions/exec";
import * as path from "path";
import { Architecture, Platform } from "../utils/platforms";
import { validateChecksum } from "./checksum/checksum";
import { OWNER, REPO, TOOL_CACHE_NAME } from "../utils/utils";
export async function downloadLatest(
platform: Platform,
arch: Architecture,
checkSum: string | undefined,
githubToken: string | undefined
): Promise<{cachedToolDir: string; version: string}> {
const artifact = `uv-${arch}-${platform}`
let downloadUrl = `https://github.com/${OWNER}/${REPO}/releases/latest/download/${artifact}`
if (platform === 'pc-windows-msvc') {
downloadUrl += '.zip'
githubToken: string | undefined,
): Promise<{ cachedToolDir: string; version: string }> {
const artifact = `uv-${arch}-${platform}`;
let downloadUrl = `https://github.com/${OWNER}/${REPO}/releases/latest/download/${artifact}`;
if (platform === "pc-windows-msvc") {
downloadUrl += ".zip";
} else {
downloadUrl += '.tar.gz'
downloadUrl += ".tar.gz";
}
core.info(`Downloading uv from "${downloadUrl}" ...`)
core.info(`Downloading uv from "${downloadUrl}" ...`);
const downloadPath = await tc.downloadTool(
downloadUrl,
undefined,
githubToken
)
let uvExecutablePath: string
let uvDir: string
if (platform === 'pc-windows-msvc') {
uvDir = await tc.extractZip(downloadPath)
githubToken,
);
let uvExecutablePath: string;
let uvDir: string;
if (platform === "pc-windows-msvc") {
uvDir = await tc.extractZip(downloadPath);
// On windows extracting the zip does not create an intermediate directory
uvExecutablePath = path.join(uvDir, 'uv.exe')
uvExecutablePath = path.join(uvDir, "uv.exe");
} else {
const extractedDir = await tc.extractTar(downloadPath)
uvDir = path.join(extractedDir, artifact)
uvExecutablePath = path.join(uvDir, 'uv')
const extractedDir = await tc.extractTar(downloadPath);
uvDir = path.join(extractedDir, artifact);
uvExecutablePath = path.join(uvDir, "uv");
}
const version = await getVersion(uvExecutablePath)
await validateChecksum(checkSum, downloadPath, arch, platform, version)
const cachedToolDir = await tc.cacheDir(uvDir, TOOL_CACHE_NAME, version, arch)
const version = await getVersion(uvExecutablePath);
await validateChecksum(checkSum, downloadPath, arch, platform, version);
const cachedToolDir = await tc.cacheDir(
uvDir,
TOOL_CACHE_NAME,
version,
arch,
);
return {cachedToolDir, version}
return { cachedToolDir, version };
}
async function getVersion(uvExecutablePath: string): Promise<string> {
@ -50,17 +55,17 @@ async function getVersion(uvExecutablePath: string): Promise<string> {
// uv 0.3.1 (be17d132a 2024-08-21)
const options: exec.ExecOptions = {
silent: !core.isDebug()
}
const execArgs = ['--version']
silent: !core.isDebug(),
};
const execArgs = ["--version"];
let output = ''
let output = "";
options.listeners = {
stdout: (data: Buffer) => {
output += data.toString()
}
}
await exec.exec(uvExecutablePath, execArgs, options)
const parts = output.split(' ')
return parts[1]
output += data.toString();
},
};
await exec.exec(uvExecutablePath, execArgs, options);
const parts = output.split(" ");
return parts[1];
}

View File

@ -1,18 +1,18 @@
import * as core from '@actions/core'
import * as tc from '@actions/tool-cache'
import * as path from 'path'
import {OWNER, REPO, TOOL_CACHE_NAME} from '../utils/utils'
import {Architecture, Platform} from '../utils/platforms'
import {validateChecksum} from './checksum/checksum'
import * as core from "@actions/core";
import * as tc from "@actions/tool-cache";
import * as path from "path";
import { OWNER, REPO, TOOL_CACHE_NAME } from "../utils/utils";
import { Architecture, Platform } from "../utils/platforms";
import { validateChecksum } from "./checksum/checksum";
export function tryGetFromToolCache(
arch: Architecture,
version: string
version: string,
): string | undefined {
core.debug(`Trying to get uv from tool cache for ${version}...`)
const cachedVersions = tc.findAllVersions(TOOL_CACHE_NAME, arch)
core.debug(`Cached versions: ${cachedVersions}`)
return tc.find(TOOL_CACHE_NAME, version, arch)
core.debug(`Trying to get uv from tool cache for ${version}...`);
const cachedVersions = tc.findAllVersions(TOOL_CACHE_NAME, arch);
core.debug(`Cached versions: ${cachedVersions}`);
return tc.find(TOOL_CACHE_NAME, version, arch);
}
export async function downloadVersion(
@ -20,32 +20,32 @@ export async function downloadVersion(
arch: Architecture,
version: string,
checkSum: string | undefined,
githubToken: string | undefined
githubToken: string | undefined,
): Promise<string> {
const artifact = `uv-${arch}-${platform}`
let downloadUrl = `https://github.com/${OWNER}/${REPO}/releases/download/${version}/${artifact}`
if (platform === 'pc-windows-msvc') {
downloadUrl += '.zip'
const artifact = `uv-${arch}-${platform}`;
let downloadUrl = `https://github.com/${OWNER}/${REPO}/releases/download/${version}/${artifact}`;
if (platform === "pc-windows-msvc") {
downloadUrl += ".zip";
} else {
downloadUrl += '.tar.gz'
downloadUrl += ".tar.gz";
}
core.info(`Downloading uv from "${downloadUrl}" ...`)
core.info(`Downloading uv from "${downloadUrl}" ...`);
const downloadPath = await tc.downloadTool(
downloadUrl,
undefined,
githubToken
)
await validateChecksum(checkSum, downloadPath, arch, platform, version)
githubToken,
);
await validateChecksum(checkSum, downloadPath, arch, platform, version);
let uvDir: string
if (platform === 'pc-windows-msvc') {
uvDir = await tc.extractZip(downloadPath)
let uvDir: string;
if (platform === "pc-windows-msvc") {
uvDir = await tc.extractZip(downloadPath);
// On windows extracting the zip does not create an intermediate directory
} else {
const extractedDir = await tc.extractTar(downloadPath)
uvDir = path.join(extractedDir, artifact)
const extractedDir = await tc.extractTar(downloadPath);
uvDir = path.join(extractedDir, artifact);
}
return await tc.cacheDir(uvDir, TOOL_CACHE_NAME, version, arch)
return await tc.cacheDir(uvDir, TOOL_CACHE_NAME, version, arch);
}

View File

@ -1,49 +1,52 @@
import * as cache from '@actions/cache'
import * as core from '@actions/core'
import * as exec from '@actions/exec'
import {STATE_CACHE_MATCHED_KEY, STATE_CACHE_KEY} from './cache/restore-cache'
import {cacheLocalPath, enableCache} from './utils/inputs'
import * as cache from "@actions/cache";
import * as core from "@actions/core";
import * as exec from "@actions/exec";
import {
STATE_CACHE_MATCHED_KEY,
STATE_CACHE_KEY,
} from "./cache/restore-cache";
import { cacheLocalPath, enableCache } from "./utils/inputs";
export async function run(): Promise<void> {
try {
if (enableCache) {
await saveCache()
await saveCache();
}
} catch (error) {
const err = error as Error
core.setFailed(err.message)
const err = error as Error;
core.setFailed(err.message);
}
process.exit(0)
process.exit(0);
}
async function saveCache(): Promise<void> {
const cacheKey = core.getState(STATE_CACHE_KEY)
const matchedKey = core.getState(STATE_CACHE_MATCHED_KEY)
const cacheKey = core.getState(STATE_CACHE_KEY);
const matchedKey = core.getState(STATE_CACHE_MATCHED_KEY);
if (!cacheKey) {
core.warning('Error retrieving cache key from state.')
return
core.warning("Error retrieving cache key from state.");
return;
} else if (matchedKey === cacheKey) {
core.info(`Cache hit occurred on key ${cacheKey}, not saving cache.`)
return
core.info(`Cache hit occurred on key ${cacheKey}, not saving cache.`);
return;
}
await pruneCache()
await pruneCache();
core.info(`Saving cache path: ${cacheLocalPath}`)
await cache.saveCache([cacheLocalPath], cacheKey)
core.info(`Saving cache path: ${cacheLocalPath}`);
await cache.saveCache([cacheLocalPath], cacheKey);
core.info(`cache saved with the key: ${cacheKey}`)
core.info(`cache saved with the key: ${cacheKey}`);
}
async function pruneCache(): Promise<void> {
const options: exec.ExecOptions = {
silent: !core.isDebug()
}
const execArgs = ['cache', 'prune', '--ci']
silent: !core.isDebug(),
};
const execArgs = ["cache", "prune", "--ci"];
core.info('Pruning cache...')
await exec.exec('uv', execArgs, options)
core.info("Pruning cache...");
await exec.exec("uv", execArgs, options);
}
run()
run();

View File

@ -1,51 +1,59 @@
import * as core from '@actions/core'
import * as path from 'path'
import {downloadVersion, tryGetFromToolCache} from './download/download-version'
import {restoreCache} from './cache/restore-cache'
import * as core from "@actions/core";
import * as path from "path";
import {
downloadVersion,
tryGetFromToolCache,
} from "./download/download-version";
import { restoreCache } from "./cache/restore-cache";
import {downloadLatest} from './download/download-latest'
import {Architecture, getArch, getPlatform, Platform} from './utils/platforms'
import { downloadLatest } from "./download/download-latest";
import {
Architecture,
getArch,
getPlatform,
Platform,
} from "./utils/platforms";
import {
cacheLocalPath,
checkSum,
enableCache,
githubToken,
version
} from './utils/inputs'
version,
} from "./utils/inputs";
async function run(): Promise<void> {
const platform = getPlatform()
const arch = getArch()
const platform = getPlatform();
const arch = getArch();
try {
if (platform === undefined) {
throw new Error(`Unsupported platform: ${process.platform}`)
throw new Error(`Unsupported platform: ${process.platform}`);
}
if (arch === undefined) {
throw new Error(`Unsupported architecture: ${process.arch}`)
throw new Error(`Unsupported architecture: ${process.arch}`);
}
const setupResult = await setupUv(
platform,
arch,
version,
checkSum,
githubToken
)
githubToken,
);
addUvToPath(setupResult.uvDir)
core.setOutput('uv-version', version)
core.info(`Successfully installed uv version ${version}`)
addUvToPath(setupResult.uvDir);
core.setOutput("uv-version", version);
core.info(`Successfully installed uv version ${version}`);
addMatchers()
setCacheDir(cacheLocalPath)
addMatchers();
setCacheDir(cacheLocalPath);
if (enableCache) {
await restoreCache(setupResult.version)
await restoreCache(setupResult.version);
}
} catch (err) {
core.setFailed((err as Error).message)
core.setFailed((err as Error).message);
}
process.exit(0)
process.exit(0);
}
async function setupUv(
@ -53,47 +61,47 @@ async function setupUv(
arch: Architecture,
versionInput: string,
checkSum: string | undefined,
githubToken: string | undefined
): Promise<{uvDir: string; version: string}> {
let installedPath: string | undefined
let cachedToolDir: string
let version: string
if (versionInput === 'latest') {
const result = await downloadLatest(platform, arch, checkSum, githubToken)
version = result.version
cachedToolDir = result.cachedToolDir
githubToken: string | undefined,
): Promise<{ uvDir: string; version: string }> {
let installedPath: string | undefined;
let cachedToolDir: string;
let version: string;
if (versionInput === "latest") {
const result = await downloadLatest(platform, arch, checkSum, githubToken);
version = result.version;
cachedToolDir = result.cachedToolDir;
} else {
version = versionInput
installedPath = tryGetFromToolCache(arch, versionInput)
version = versionInput;
installedPath = tryGetFromToolCache(arch, versionInput);
if (installedPath) {
core.info(`Found uv in tool-cache for ${versionInput}`)
return {uvDir: installedPath, version}
core.info(`Found uv in tool-cache for ${versionInput}`);
return { uvDir: installedPath, version };
}
cachedToolDir = await downloadVersion(
platform,
arch,
versionInput,
checkSum,
githubToken
)
githubToken,
);
}
return {uvDir: cachedToolDir, version}
return { uvDir: cachedToolDir, version };
}
function addUvToPath(cachedPath: string): void {
core.addPath(cachedPath)
core.info(`Added ${cachedPath} to the path`)
core.addPath(cachedPath);
core.info(`Added ${cachedPath} to the path`);
}
function setCacheDir(cacheLocalPath: string): void {
core.exportVariable('UV_CACHE_DIR', cacheLocalPath)
core.info(`Set UV_CACHE_DIR to ${cacheLocalPath}`)
core.exportVariable("UV_CACHE_DIR", cacheLocalPath);
core.info(`Set UV_CACHE_DIR to ${cacheLocalPath}`);
}
function addMatchers(): void {
const matchersPath = path.join(__dirname, `..${path.sep}..`, '.github')
core.info(`##[add-matcher]${path.join(matchersPath, 'python.json')}`)
const matchersPath = path.join(__dirname, `..${path.sep}..`, ".github");
core.info(`##[add-matcher]${path.join(matchersPath, "python.json")}`);
}
run()
run();

View File

@ -1,65 +1,65 @@
import * as github from '@actions/github'
import * as core from '@actions/core'
import * as github from "@actions/github";
import * as core from "@actions/core";
import {OWNER, REPO} from './utils/utils'
import {createReadStream, promises as fs} from 'fs'
import * as readline from 'readline'
import * as semver from 'semver'
import { OWNER, REPO } from "./utils/utils";
import { createReadStream, promises as fs } from "fs";
import * as readline from "readline";
import * as semver from "semver";
import {updateChecksums} from './download/checksum/update-known-checksums'
import { updateChecksums } from "./download/checksum/update-known-checksums";
async function run(): Promise<void> {
const checksumFilePath = process.argv.slice(2)[0]
const defaultVersionFilePath = process.argv.slice(2)[1]
const github_token = process.argv.slice(2)[2]
const checksumFilePath = process.argv.slice(2)[0];
const defaultVersionFilePath = process.argv.slice(2)[1];
const github_token = process.argv.slice(2)[2];
const octokit = github.getOctokit(github_token)
const octokit = github.getOctokit(github_token);
const response = await octokit.paginate(octokit.rest.repos.listReleases, {
owner: OWNER,
repo: REPO
})
const downloadUrls: string[] = response.flatMap(release =>
repo: REPO,
});
const downloadUrls: string[] = response.flatMap((release) =>
release.assets
.filter(asset => asset.name.endsWith('.sha256'))
.map(asset => asset.browser_download_url)
)
await updateChecksums(checksumFilePath, downloadUrls)
.filter((asset) => asset.name.endsWith(".sha256"))
.map((asset) => asset.browser_download_url),
);
await updateChecksums(checksumFilePath, downloadUrls);
const latestVersion = response
.map(release => release.tag_name)
.sort(semver.rcompare)[0]
core.setOutput('latest-version', latestVersion)
await updateDefaultVersion(defaultVersionFilePath, latestVersion)
.map((release) => release.tag_name)
.sort(semver.rcompare)[0];
core.setOutput("latest-version", latestVersion);
await updateDefaultVersion(defaultVersionFilePath, latestVersion);
}
async function updateDefaultVersion(
filePath: string,
latestVersion: string
latestVersion: string,
): Promise<void> {
const fileStream = createReadStream(filePath)
const fileStream = createReadStream(filePath);
const rl = readline.createInterface({
input: fileStream
})
input: fileStream,
});
let foundDescription = false
const lines = []
let foundDescription = false;
const lines = [];
for await (let line of rl) {
if (
!foundDescription &&
line.includes("description: 'The version of uv to install'")
) {
foundDescription = true
} else if (foundDescription && line.includes('default: ')) {
line = line.replace(/'[^']*'/, `'${latestVersion}'`)
foundDescription = false
foundDescription = true;
} else if (foundDescription && line.includes("default: ")) {
line = line.replace(/'[^']*'/, `'${latestVersion}'`);
foundDescription = false;
}
lines.push(line)
lines.push(line);
}
await fs.writeFile(filePath, lines.join('\n'))
await fs.writeFile(filePath, lines.join("\n"));
}
run()
run();

View File

@ -1,9 +1,9 @@
import * as core from '@actions/core'
import * as core from "@actions/core";
export const version = core.getInput('version')
export const checkSum = core.getInput('checksum')
export const enableCache = core.getInput('enable-cache') === 'true'
export const cacheSuffix = core.getInput('cache-suffix') || ''
export const cacheLocalPath = core.getInput('cache-local-path')
export const githubToken = core.getInput('github-token')
export const cacheDependencyGlob = core.getInput('cache-dependency-glob')
export const version = core.getInput("version");
export const checkSum = core.getInput("checksum");
export const enableCache = core.getInput("enable-cache") === "true";
export const cacheSuffix = core.getInput("cache-suffix") || "";
export const cacheLocalPath = core.getInput("cache-local-path");
export const githubToken = core.getInput("github-token");
export const cacheDependencyGlob = core.getInput("cache-dependency-glob");

View File

@ -1,33 +1,33 @@
export type Platform =
| 'unknown-linux-gnu'
| 'unknown-linux-musl'
| 'unknown-linux-musleabihf'
| 'apple-darwin'
| 'pc-windows-msvc'
export type Architecture = 'i686' | 'x86_64' | 'aarch64'
| "unknown-linux-gnu"
| "unknown-linux-musl"
| "unknown-linux-musleabihf"
| "apple-darwin"
| "pc-windows-msvc";
export type Architecture = "i686" | "x86_64" | "aarch64";
export function getArch(): Architecture | undefined {
const arch = process.arch
const archMapping: {[key: string]: Architecture} = {
ia32: 'i686',
x64: 'x86_64',
arm64: 'aarch64'
}
const arch = process.arch;
const archMapping: { [key: string]: Architecture } = {
ia32: "i686",
x64: "x86_64",
arm64: "aarch64",
};
if (arch in archMapping) {
return archMapping[arch]
return archMapping[arch];
}
}
export function getPlatform(): Platform | undefined {
const platform = process.platform
const platformMapping: {[key: string]: Platform} = {
linux: 'unknown-linux-gnu',
darwin: 'apple-darwin',
win32: 'pc-windows-msvc'
}
const platform = process.platform;
const platformMapping: { [key: string]: Platform } = {
linux: "unknown-linux-gnu",
darwin: "apple-darwin",
win32: "pc-windows-msvc",
};
if (platform in platformMapping) {
return platformMapping[platform]
return platformMapping[platform];
}
}

View File

@ -1,3 +1,3 @@
export const REPO = 'uv'
export const OWNER = 'astral-sh'
export const TOOL_CACHE_NAME = 'uv'
export const REPO = "uv";
export const OWNER = "astral-sh";
export const TOOL_CACHE_NAME = "uv";