forked from dotnet/crank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVersionChecker.cs
67 lines (57 loc) · 2.61 KB
/
VersionChecker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NuGet.Versioning;
namespace Microsoft.Crank.Controller
{
public static class VersionChecker
{
static TimeSpan CacheTimeout = TimeSpan.FromDays(1);
static string PackageVersionUrl = "https://api.nuget.org/v3-flatcontainer/microsoft.crank.controller/index.json";
public static async Task CheckUpdateAsync(HttpClient client)
{
// The NuGet version is cached in a local file for a day (CacheTimeout) so we don't query nuget.org
// on every run.
try
{
var versionFilename = Path.Combine(Path.GetTempPath(), ".crank", "controller", "version.txt");
if (!File.Exists(versionFilename))
{
Directory.CreateDirectory(Path.GetDirectoryName(versionFilename));
}
NuGetVersion latest;
// If the file is older than CacheTimeout, get the version from NuGet.org
if (DateTime.UtcNow - new FileInfo(versionFilename).LastWriteTimeUtc > CacheTimeout)
{
var content = await client.GetStringAsync(PackageVersionUrl);
var document = JObject.Parse(content);
var versions = (JArray)document["versions"];
latest = versions.Select(x => new NuGetVersion(x.ToString())).Max();
File.WriteAllText(versionFilename, latest.ToNormalizedString());
}
else
{
latest = NuGetVersion.Parse(File.ReadAllText(versionFilename));
}
var attribute = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>();
var current = new NuGetVersion(attribute.InformationalVersion);
if (latest > current)
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine($"A new version is available on NuGet.org ({latest}). Run 'dotnet tool update Microsoft.Crank.Controller -g --version \"0.2.0-*\"' to update");
Console.ResetColor();
}
}
catch
{
}
}
}
}