diff --git a/.github/workflows/post_publish.yml b/.github/workflows/post_publish.yml new file mode 100644 index 00000000..196ed172 --- /dev/null +++ b/.github/workflows/post_publish.yml @@ -0,0 +1,32 @@ +name: post_publish + +on: + release: + types: [published] + +jobs: + update-dl-version: + name: update dl.deno.land version + runs-on: ubuntu-22.04 + if: github.repository == 'denoland/fresh' + steps: + - name: Checkout repo + uses: actions/checkout@v3 + + - name: Authenticate with Google Cloud + uses: google-github-actions/auth@v1 + with: + project_id: denoland + credentials_json: ${{ secrets.GCP_SA_KEY }} + export_environment_variables: true + create_credentials_file: true + + - name: Setup gcloud + uses: google-github-actions/setup-gcloud@v1 + with: + project_id: denoland + + - name: Upload version file to dl.deno.land + run: | + cat versions.json | jq -r ".[0]" > release-latest.txt + gsutil -h "Cache-Control: no-cache" cp release-latest.txt gs://dl.deno.land/fresh/release-latest.txt diff --git a/docs/canary/concepts/updating.md b/docs/canary/concepts/updating.md new file mode 100644 index 00000000..83c7aaeb --- /dev/null +++ b/docs/canary/concepts/updating.md @@ -0,0 +1,128 @@ +--- +description: | + New versions of Fresh are regularly released. This page explains how to update your project. +--- + +Fresh constists of multiple pieces which are independently versioned and +released. + +- Fresh (https://deno.land/x/fresh) +- Preact (https://esm.sh/preact) +- preact-render-to-string (https://esm.sh/preact-render-to-string) + +Some plugins also have their own dependencies that can be updated independently. + +- Twind (https://esm.sh/twind) (for the twind plugin) + +For the most part these pieces can be updated independently. Certain versions of +Fresh may require a minimum version of a given dependency. This is documented +below. + +| Fresh version | Preact | preact-render-to-string | Deno | +| ------------- | ----------------- | ----------------------- | --------- | +| 1.0.0-1.0.2 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.23.0 | +| 1.1.0-1.1.5 | >=10.8.1 <11.0.0 | >=5.2.0 <6.0.0 | >= 1.25.0 | +| 1.2.0 | >=10.15.0 <11.0.0 | >=6.1.0 | >= 1.25.0 | + +## Updating dependencies + +To update your dependencies, you have two options: + +- Run the fresh updater to update your project dependencies. +- Manually update the dependency versions in your `deno.json` file. + +### Auto updater + +The auto updater is a command line tool that will update your project's +`deno.json` file to the latest versions of Fresh and its dependencies. It may +also contain code mods for your project that will update your code to the latest +recommended patterns for Fresh projects. + +To run the auto updater, run the following command from the root of your +project: + +```bash +$ deno run -A -r https://fresh.deno.dev/update . +``` + +You will be prompted to confirm the changes that will be made to your project. + +### Manual update + +To manually update your project's dependencies, you can edit the `deno.json` +file in the root of your projects directory. Dependency versions are encoded +into the URLs in this file. For example, here is how to update a project from +Fresh 1.0.2 to 1.1.3, and update Preact to the latest version: + +```diff + { + "imports": { +- "$fresh/": "https://deno.land/x/fresh@1.0.2/", ++ "$fresh/": "https://deno.land/x/fresh@1.1.5/", + +- "preact": "https://esm.sh/preact@10.8.1", +- "preact/": "https://esm.sh/preact@10.8.1/", ++ "preact": "https://esm.sh/preact@10.11.0", ++ "preact/": "https://esm.sh/preact@10.11.0/", + +- "preact-render-to-string": "https://esm.sh/*preact-render-to-string@5.2.0", ++ "preact-render-to-string": "https://esm.sh/*preact-render-to-string@6.1.0", + + "twind": "https://esm.sh/twind@0.16.17", + "twind/": "https://esm.sh/twind@0.16.17/" + } + } +``` + +## Automatic update checks + +Fresh will periodically check if a new Fresh version is available if it's +running outside of CI. This happens once per day and can be disabled by setting +the `FRESH_NO_UPDATE_CHECK=true` environment variable. + +## Code mods + +Code mods are small scripts that can be run to update your project's code to +match the latest recommended patterns for Fresh projects. Code mods can be run +through the auto updater. Sometimes the code mod can not cover all cases, so you +may need to manually update some code. This section explains the code mods +currently available. + +### Classical JSX -> Automatic JSX + +> This code mod is only available in Fresh 1.1.0 and above. + +The classical JSX transform that relies on a `/** @jsx h */` pragma is no longer +the recommended way to use JSX in Fresh projects. Instead, starting with version +1.1.0, Fresh projects should use the automatic JSX transform that requires no +JSX pragma or preact import. + +```diff +- /** @jsx h */ +- import { h } from "preact"; + + export default function Page() { + return
Hello world!
; + } +``` + +This code mod will update your deno.json file to include the relevant compiler +options to enable the automatic JSX transform. It will then go through your +project and remove any `/** @jsx h */` pragmas and `import { h } from "preact"` +statements. + +### Classic twind -> Twind plugin + +> This code mod is only available in Fresh 1.1.0 and above. + +Fresh version 1.1.0 introduced a new plugin for using twind with Fresh. This +plugin is much nicer to use than the raw twind integration that was previously +available. + +This code mod will update your project to use the new twind plugin. It will +update your `main.ts` file to import the twind plugin and add it to the plugins +array. It will also update your files to remove many unnecessary uses of the +`tw` function, and remove unnecessary twind imports. While the code mod can +handle most cases, you may need to manually update some code. Additionally you +will need to manually update your `twind.config.ts` if you use a custom +configuration. diff --git a/docs/toc.ts b/docs/toc.ts index 2402ff6e..5b942a4c 100644 --- a/docs/toc.ts +++ b/docs/toc.ts @@ -56,7 +56,7 @@ const toc: RawTableOfContents = { ["data-fetching", "Data fetching", "link:latest"], ["deployment", "Deployment", "link:latest"], ["plugins", "Plugins", "link:latest"], - ["updating", "Updating Fresh", "link:latest"], + ["updating", "Updating Fresh", "link:canary"], ["app-wrapper", "Application wrapper", "link:latest"], ["server-configuration", "Server configuration", "link:canary"], ], diff --git a/src/dev/deps.ts b/src/dev/deps.ts index 39b7e0b2..c6cfcb34 100644 --- a/src/dev/deps.ts +++ b/src/dev/deps.ts @@ -11,6 +11,7 @@ export { SEP, toFileUrl, } from "https://deno.land/std@0.193.0/path/mod.ts"; +export { DAY } from "https://deno.land/std@0.193.0/datetime/constants.ts"; export * as colors from "https://deno.land/std@0.193.0/fmt/colors.ts"; export { walk, WalkError } from "https://deno.land/std@0.193.0/fs/walk.ts"; export { parse } from "https://deno.land/std@0.193.0/flags/mod.ts"; diff --git a/src/dev/mod.ts b/src/dev/mod.ts index 8103d1cf..162c6d72 100644 --- a/src/dev/mod.ts +++ b/src/dev/mod.ts @@ -1,4 +1,6 @@ +import { updateCheck } from "./update_check.ts"; import { + DAY, dirname, fromFileUrl, gte, @@ -164,6 +166,9 @@ export default manifest; export async function dev(base: string, entrypoint: string) { ensureMinDenoVersion(); + // Run update check in background + updateCheck(DAY).catch(() => {}); + entrypoint = new URL(entrypoint, base).href; const dir = dirname(fromFileUrl(base)); diff --git a/src/dev/update_check.ts b/src/dev/update_check.ts new file mode 100644 index 00000000..5cc45834 --- /dev/null +++ b/src/dev/update_check.ts @@ -0,0 +1,121 @@ +import { colors, join } from "./deps.ts"; + +interface CheckFile { + last_checked: string; + latest_version: string; + current_version: string; +} + +function getHomeDir(): string | null { + switch (Deno.build.os) { + case "linux": { + const xdg = Deno.env.get("XDG_CACHE_HOME"); + if (xdg) return xdg; + + const home = Deno.env.get("HOME"); + if (home) return `${home}/.cache`; + break; + } + + case "darwin": { + const home = Deno.env.get("HOME"); + if (home) return `${home}/Library/Caches`; + break; + } + + case "windows": + return Deno.env.get("LOCALAPPDATA") ?? null; + } + + return null; +} + +function getFreshCacheDir(): string | null { + const home = getHomeDir(); + if (home) return join(home, "fresh"); + return null; +} + +async function fetchLatestVersion() { + const res = await fetch("https://dl.deno.land/fresh/release-latest.txt"); + if (res.ok) { + return (await res.text()).trim().replace(/^v/, ""); + } + + throw new Error(`Could not fetch latest version.`); +} + +export async function updateCheck( + interval: number, + getCacheDir = getFreshCacheDir, + getLatestVersion = fetchLatestVersion, +) { + // Skip update checks on CI or Deno Deploy + if ( + Deno.env.get("CI") === "true" || + Deno.env.get("FRESH_NO_UPDATE_CHECK") === "true" || + Deno.env.get("DENO_DEPLOYMENT_ID") + ) { + return; + } + + const home = getCacheDir(); + if (!home) return; + const filePath = join(home, "latest.json"); + try { + await Deno.mkdir(home, { recursive: true }); + } catch (err) { + if (!(err instanceof Deno.errors.AlreadyExists)) { + throw err; + } + } + + const versions = (await import("../../versions.json", { + "assert": { type: "json" }, + })).default as string[]; + + let checkFile: CheckFile = { + current_version: versions[0], + latest_version: versions[0], + last_checked: new Date(0).toISOString(), + }; + try { + const text = await Deno.readTextFile(filePath); + checkFile = JSON.parse(text); + } catch (err) { + if (!(err instanceof Deno.errors.NotFound)) { + throw err; + } + } + + // Only check in the specificed interval + if (Date.now() >= new Date(checkFile.last_checked).getTime() + interval) { + try { + checkFile.latest_version = await getLatestVersion(); + checkFile.last_checked = new Date().toISOString(); + } catch (err) { + // Update check is optional and shouldn't abort the program. + console.error( + colors.red(` Update check failed: `) + err.message, + ); + return; + } + } + + if (checkFile.current_version !== checkFile.latest_version) { + const current = colors.bold(colors.rgb8(checkFile.current_version, 208)); + const latest = colors.bold(colors.rgb8(checkFile.latest_version, 121)); + console.log( + ` Fresh ${latest} is available. You're on ${current}`, + ); + console.log( + colors.dim( + ` To upgrade, run: `, + ) + colors.dim(`deno run -A -r https://fresh.deno.dev/update .`), + ); + console.log(); + } + + const raw = JSON.stringify(checkFile, null, 2); + await Deno.writeTextFile(filePath, raw); +} diff --git a/tests/cli_update_check_test.ts b/tests/cli_update_check_test.ts new file mode 100644 index 00000000..85404302 --- /dev/null +++ b/tests/cli_update_check_test.ts @@ -0,0 +1,156 @@ +import { colors, join } from "../src/server/deps.ts"; +import { + assertEquals, + assertMatch, + assertNotMatch, +} from "$std/testing/asserts.ts"; +import versions from "../versions.json" assert { type: "json" }; + +Deno.test({ + name: "stores update check file in $HOME/fresh", + async fn() { + const tmpDirName = await Deno.makeTempDir(); + const filePath = join(tmpDirName, "latest.json"); + + await new Deno.Command(Deno.execPath(), { + args: ["run", "-A", "./tests/fixture_update_check/mod.ts"], + env: { + CI: "false", + HOME: tmpDirName, + }, + }).output(); + + const text = JSON.parse(await Deno.readTextFile(filePath)); + assertEquals(text, { + current_version: versions[0], + latest_version: "99.99.999", + last_checked: text.last_checked, + }); + + await Deno.remove(tmpDirName, { recursive: true }); + }, +}); + +Deno.test({ + name: "skips update check on specific environment variables", + async fn(t) { + const envs = ["FRESH_NO_UPDATE_CHECK", "CI", "DENO_DEPLOYMENT_ID"]; + + for (const env of envs) { + await t.step(`checking ${env}`, async () => { + const tmpDirName = await Deno.makeTempDir(); + const out = await new Deno.Command(Deno.execPath(), { + args: ["run", "-A", "./tests/fixture_update_check/mod.ts"], + env: { + [env]: "true", + HOME: tmpDirName, + LATEST_VERSION: "1.30.0", + }, + }).output(); + + const decoder = new TextDecoder(); + const stdout = colors.stripColor(decoder.decode(out.stdout)); + assertNotMatch(stdout, /Fresh 1\.30\.0 is available/); + + await Deno.remove(tmpDirName, { recursive: true }); + }); + } + }, +}); + +Deno.test({ + name: "shows update message on version mismatch", + async fn() { + const tmpDirName = await Deno.makeTempDir(); + const filePath = join(tmpDirName, "latest.json"); + + await Deno.writeTextFile( + filePath, + JSON.stringify({ + current_version: "1.1.0", + latest_version: "1.1.0", + last_checked: new Date(0).toISOString(), + }), + ); + + const out = await new Deno.Command(Deno.execPath(), { + args: ["run", "-A", "./tests/fixture_update_check/mod.ts"], + env: { + CI: "false", + HOME: tmpDirName, + LATEST_VERSION: "1.30.0", + }, + }).output(); + + const decoder = new TextDecoder(); + + const stdout = colors.stripColor(decoder.decode(out.stdout)); + assertMatch(stdout, /Fresh 1\.30\.0 is available/); + + // Updates check file + const text = JSON.parse(await Deno.readTextFile(filePath)); + assertEquals(text, { + current_version: "1.1.0", + latest_version: "1.30.0", + last_checked: text.last_checked, + }); + + await Deno.remove(tmpDirName, { recursive: true }); + }, + sanitizeResources: false, +}); + +Deno.test({ + name: "only fetch new version defined by interval", + async fn(t) { + const tmpDirName = await Deno.makeTempDir(); + const decoder = new TextDecoder(); + + await t.step("fetches latest version initially", async () => { + const out = await new Deno.Command(Deno.execPath(), { + args: ["run", "-A", "./tests/fixture_update_check/mod.ts"], + env: { + CI: "false", + UPDATE_INTERVAL: "100000", + HOME: tmpDirName, + LATEST_VERSION: "1.30.0", + }, + }).output(); + + const stdout = colors.stripColor(decoder.decode(out.stdout)); + assertMatch(stdout, /fetching latest version/); + }); + + await t.step("should not fetch if interval has not passed", async () => { + const out = await new Deno.Command(Deno.execPath(), { + args: ["run", "-A", "./tests/fixture_update_check/mod.ts"], + env: { + CI: "false", + UPDATE_INTERVAL: "100000", + HOME: tmpDirName, + LATEST_VERSION: "1.30.0", + }, + }).output(); + + const stdout = colors.stripColor(decoder.decode(out.stdout)); + assertNotMatch(stdout, /fetching latest version/); + }); + + await t.step("fetches if interval has passed", async () => { + const out = await new Deno.Command(Deno.execPath(), { + args: ["run", "-A", "./tests/fixture_update_check/mod.ts"], + env: { + CI: "false", + UPDATE_INTERVAL: "1 ", + HOME: tmpDirName, + LATEST_VERSION: "1.30.0", + }, + }).output(); + + const stdout = colors.stripColor(decoder.decode(out.stdout)); + assertMatch(stdout, /fetching latest version/); + }); + + await Deno.remove(tmpDirName, { recursive: true }); + }, +}); diff --git a/tests/fixture_update_check/mod.ts b/tests/fixture_update_check/mod.ts new file mode 100644 index 00000000..7f98632b --- /dev/null +++ b/tests/fixture_update_check/mod.ts @@ -0,0 +1,10 @@ +import { updateCheck } from "$fresh/src/dev/update_check.ts"; + +// deno-lint-ignore require-await +async function getLatestVersion() { + console.log("fetching latest version"); + return Deno.env.get("LATEST_VERSION") ?? "99.99.999"; +} + +const interval = +(Deno.env.get("UPDATE_INTERVAL") ?? 1000); +await updateCheck(interval, () => Deno.env.get("HOME")!, getLatestVersion);