|
| 1 | +const fs = require('fs-extra') |
| 2 | +const path = require('path') |
| 3 | +const fsCachePath = path.resolve(__dirname, '.version') |
| 4 | + |
1 | 5 | module.exports = async function getVersions () {
|
2 |
| - const current = require(`../../package.json`).version |
3 | 6 | let latest
|
4 |
| - if (process.env.VUE_CLI_LATEST_VERSION) { |
5 |
| - // cached value |
6 |
| - latest = process.env.VUE_CLI_LATEST_VERSION |
7 |
| - } else if (process.env.VUE_CLI_TEST || process.env.VUE_CLI_DEBUG) { |
8 |
| - // test/debug, use local version |
9 |
| - latest = process.env.VUE_CLI_LATEST_VERSION = current |
10 |
| - } else { |
11 |
| - const getPackageVersion = require('./getPackageVersion') |
12 |
| - const res = await getPackageVersion('vue-cli-version-marker', 'latest') |
13 |
| - if (res.statusCode === 200) { |
14 |
| - latest = process.env.VUE_CLI_LATEST_VERSION = res.body.version |
15 |
| - } else { |
16 |
| - // fallback to local version |
17 |
| - latest = process.env.VUE_CLI_LATEST_VERSION = current |
| 7 | + const current = require(`../../package.json`).version |
| 8 | + if (process.env.VUE_CLI_TEST || process.env.VUE_CLI_DEBUG) { |
| 9 | + return { |
| 10 | + latest: current, |
| 11 | + current |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + if (fs.existsSync(fsCachePath)) { |
| 16 | + // if we haven't check for a new version in a week, force a full check |
| 17 | + // before proceeding. |
| 18 | + const lastChecked = (await fs.stat(fsCachePath)).mtimeMs |
| 19 | + const daysPassed = (Date.now() - lastChecked) / (60 * 60 * 1000 * 24) |
| 20 | + if (daysPassed > 7) { |
| 21 | + await getAndCacheLatestVersion(current) |
18 | 22 | }
|
| 23 | + latest = await fs.readFile(fsCachePath, 'utf-8') |
| 24 | + } else { |
| 25 | + // if the cache file doesn't exist, this is likely a fresh install |
| 26 | + // so no need to check |
| 27 | + latest = current |
19 | 28 | }
|
| 29 | + |
| 30 | + // Do a check in the background. The cached file will be used for the next |
| 31 | + // startup within a week. |
| 32 | + getAndCacheLatestVersion(current) |
| 33 | + |
20 | 34 | return {
|
21 | 35 | current,
|
22 | 36 | latest
|
23 | 37 | }
|
24 | 38 | }
|
| 39 | + |
| 40 | +// fetch the latest version and save it on disk |
| 41 | +// so that it is available immediately next time |
| 42 | +let sentCheckRequest = false |
| 43 | +async function getAndCacheLatestVersion (current) { |
| 44 | + if (sentCheckRequest) { |
| 45 | + return |
| 46 | + } |
| 47 | + sentCheckRequest = true |
| 48 | + const getPackageVersion = require('./getPackageVersion') |
| 49 | + const res = await getPackageVersion('vue-cli-version-marker', 'latest') |
| 50 | + if (res.statusCode === 200) { |
| 51 | + const { version } = res.body |
| 52 | + if (version !== current) { |
| 53 | + await fs.writeFile(fsCachePath, version) |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments