public async Task CheckVersion() { try { GithubVersion latest = await VersionCheck.GetLatestVersionAsync("Zingabopp", "MultiplayerExtensions"); Log?.Debug($"Latest version is {latest}, released on {latest.ReleaseDate.ToShortDateString()}"); if (PluginMetadata != null) { SemVer.Version currentVer = PluginMetadata.Version; SemVer.Version latestVersion = new SemVer.Version(latest.ToString()); bool updateAvailable = new SemVer.Range($">{currentVer}").IsSatisfied(latestVersion); if (updateAvailable) { Log?.Info($"An update is available!\nNew mod version: {latestVersion}\nCurrent mod version: {currentVer}"); } } } catch (ReleaseNotFoundException ex) { Log?.Warn(ex.Message); } catch (Exception ex) { Log?.Warn($"Error checking latest version: {ex.Message}"); Log?.Debug(ex); } }
public void UpdateVersion(SemVer.Version version) { if (version != null) { Version = version; } }
private bool FetchData(Version version) { try { if (Config.GetDevReleases || !String.IsNullOrWhiteSpace(version.PreRelease)) { LatestRelease = gClient.Repository.Release.GetAll("antonpup", "Aurora", new ApiOptions { PageCount = 1, PageSize = 1 }).Result[0]; } else { LatestRelease = gClient.Repository.Release.GetLatest("antonpup", "Aurora").Result; } //Console.WriteLine(reply); } catch (Exception exc) { updateState = UpdateStatus.Error; return(false); } return(true); }
private async Task <PackageInfo> GetBestMatchPackageVersionsAsync(string registry, bool includePrerelease, string packageId, SemVer.Range range) { PackageOption option = new PackageOption { packageId = packageId, includePrerelease = includePrerelease, registry = registry }; Console.WriteLine($"Try to find best match: {packageId}: {range.ToString()}"); IEnumerable <string> versionValues = await GetPackageVersionAsync(option.packageId, option.registry, option.includePrerelease); IEnumerable <SemVer.Version> versions = versionValues?.Select(x => new SemVer.Version(x, true)); if (versions == null) { return(null); } SemVer.Version bestMatchVersion = range.MaxSatisfying(versions); if (bestMatchVersion == null) { bestMatchVersion = versions.OrderByDescending(x => x).FirstOrDefault(); } return(new PackageInfo { packageId = packageId, packageVersion = bestMatchVersion }); }
/// <summary> /// Compares <see langword="this"/> to the <see cref="Version"/> in <paramref name="other"/> using <see cref="Version.CompareTo(Version)"/>. /// </summary> /// <remarks> /// The storage method of <see langword="this"/> must be <see cref="StoredAs.SemVer"/>, else an <see cref="InvalidOperationException"/> will /// be thrown. /// </remarks> /// <param name="other">the <see cref="Version"/> to compare to</param> /// <returns>less than 0 if <paramref name="other"/> is considered bigger than <see langword="this"/>, 0 if equal, and greater than zero if smaller</returns> /// <seealso cref="CompareTo(AlmostVersion)"/> public int CompareTo(Version other) { if (StorageMode != StoredAs.SemVer) throw new InvalidOperationException("Cannot compare a SemVer version with an AlmostVersion stored as a string!"); return SemverValue.CompareTo(other); }
IEnumerator CheckVersion() { Plugin.log.Info("Checking for updates..."); UnityWebRequest www = SongDownloader.GetRequestForUrl($"https://api.github.com/repos/andruzzzhka/BeatSaberMultiplayer/releases"); www.timeout = 10; yield return(www.SendWebRequest()); if (!www.isNetworkError && !www.isHttpError) { JSONNode releases = JSON.Parse(www.downloadHandler.text); JSONNode latestRelease = releases[0]; SemVer.Version currentVer = IPA.Loader.PluginManager.GetPlugin("Beat Saber Multiplayer").Version; SemVer.Version githubVer = new SemVer.Version(latestRelease["tag_name"], true); bool newTag = new SemVer.Range($">{currentVer}").IsSatisfied(githubVer); if (newTag) { Plugin.log.Info($"An update for the mod is available!\nNew mod version: {(string)latestRelease["tag_name"]}\nCurrent mod version: {currentVer}"); _newVersionText.gameObject.SetActive(true); _newVersionText.text = $"Version {(string)latestRelease["tag_name"]}\n of the mod is available!\nCurrent mod version: {currentVer}"; _newVersionText.alignment = TextAlignmentOptions.Center; } } }
public static Tuple <string, SemVer.Version> DownloadPackage( string packageId, string version, bool force = false) { var cacheRootPath = GetPackageCacheRoot(); if (Directory.Exists(cacheRootPath) == false) { Directory.CreateDirectory(cacheRootPath); } var ret = NuGet.CommandLine.Program.Main( new[] { "install", packageId, "-Version", version, "-Prerelease", "-Source", "nuget.org", "-NonInteractive", "-OutputDirectory", cacheRootPath }); if (ret != 0) { throw new InvalidOperationException("Nuget exited with error code: " + ret); } var packagePath = Path.Combine(cacheRootPath, packageId + "." + version); if (Directory.Exists(packagePath) == false) { throw new InvalidOperationException("Cannot find the package nuget downloaded: " + packagePath); } var ver = new SemVer.Version(version, true); return(Tuple.Create(packagePath, ver)); }
private static HostedGameData GenerateAnnounce() { var sessionManager = MpSession.SessionManager; var localPlayer = sessionManager.localPlayer; var connectedPlayers = sessionManager.connectedPlayers; if (_mpExVersion == null) { _mpExVersion = MpExHelper.GetInstalledVersion(); if (_mpExVersion != null) { Plugin.Log?.Info($"Detected MultiplayerExtensions, version {_mpExVersion}"); } } var lobbyAnnounce = new HostedGameData() { ServerCode = _lobbyCode, GameName = MpSession.GetHostGameName(), OwnerId = localPlayer.userId, OwnerName = localPlayer.userName, PlayerCount = MpSession.GetPlayerCount(), PlayerLimit = MpSession.GetPlayerLimit(), IsModded = localPlayer.HasState("modded") || localPlayer.HasState("customsongs") || _mpExVersion != null, LobbyState = MpLobbyStatePatch.LobbyState, LevelId = _level?.levelID, SongName = _level?.songName, SongAuthor = _level?.songAuthorName, Difficulty = _difficulty, Platform = MpLocalPlayer.PlatformId, MasterServerHost = MpConnect.LastUsedMasterServer != null ? MpConnect.LastUsedMasterServer.hostName : null, MasterServerPort = MpConnect.LastUsedMasterServer != null ? MpConnect.LastUsedMasterServer.port : MpConnect.DEFAULT_MASTER_PORT, MpExVersion = _mpExVersion }; lobbyAnnounce.Players = new List <HostedGamePlayer>(); lobbyAnnounce.Players.Add(new HostedGamePlayer() { SortIndex = localPlayer.sortIndex, UserId = localPlayer.userId, UserName = localPlayer.userName, IsHost = localPlayer.isConnectionOwner, Latency = localPlayer.currentLatency }); foreach (var connectedPlayer in connectedPlayers) { lobbyAnnounce.Players.Add(new HostedGamePlayer() { SortIndex = connectedPlayer.sortIndex, UserId = connectedPlayer.userId, UserName = connectedPlayer.userName, IsHost = connectedPlayer.isConnectionOwner, Latency = connectedPlayer.currentLatency }); } return(lobbyAnnounce); }
internal Artifact(Product product, Version version, string downloadUrl, ArtifactBuildState state, string buildHash) { ProductName = product.ProductName; Version = version; DownloadUrl = product?.PatchDownloadUrl(downloadUrl); State = state; BuildHash = buildHash; }
private static async Task <IEnumerable <Release> > GetReleases() { var releases = (await GitHubClient.Repository.Release.GetAll(REPO_ID).ConfigureAwait(false)) .Where(r => Version.TryParse(r.TagName, out Version version) && (version > VersionLimit)); return(releases.OrderByDescending(r => r.CreatedAt.Ticks)); }
public ExtendedPlayer(IConnectedPlayer player, string platformID, Platform platform, SemVer.Version mpexVersion, Color playerColor) { _connectedPlayer = player; this.platformID = platformID; this.platform = platform; this.mpexVersion = mpexVersion; this.playerColor = playerColor; }
public SagaVersion(string version) { if (version is null) { throw new System.ArgumentNullException(nameof(version)); } Version = new Version(version); }
public string GetSatisfyingSdkVersion( ISourceRepo sourceRepo, string runtimeVersion, IEnumerable <string> availableSdks) { string sdkVersion; if (sourceRepo.FileExists(DotNetCoreConstants.GlobalJsonFileName)) { var globalJsonContent = sourceRepo.ReadFile( Path.Combine(sourceRepo.RootPath, DotNetCoreConstants.GlobalJsonFileName)); _logger.LogDebug( "Detected presence of global.json file with content {globalJsonContent}", globalJsonContent); var globalJsonModel = JsonConvert.DeserializeObject <GlobalJsonModel>(globalJsonContent); sdkVersion = GetSatisfyingSdkVersion(globalJsonModel, availableSdks); _logger.LogDebug( "Resolved sdk version to {resolvedSdkVersion} based on global.json file and available sdk versions", sdkVersion); } else { // As per global.json spec, if a global.json file is not present, then roll forward policy is // considered as 'latestMajor'. This can cause end users apps to fail since in this case even prelreease // versions are considered. So here we minimize the impact by relying on the runtime version instead. // We choose only the 'major' and 'minor' part of the runtime version. // For example, 2.1.14 of runtime will result in a latest minor sdk in '1', for example // 2.1.202 or 2.1.400 var version = new SemVer.Version(runtimeVersion); var globalJsonModel = new GlobalJsonModel { Sdk = new SdkModel { Version = $"{version.Major}.{version.Minor}.100", // Get latest feature and patch of the version RollForward = RollForwardPolicy.LatestFeature, AllowPreRelease = true, }, }; _logger.LogDebug( "global.json file was not find in the repo, so choosing an sdk version which satisfies the " + "version {defaultSdkVersion}, roll forward policy of {defaultRollForwardPolicy} and " + "allowPrerelease value of {defaultAllowPrerelease}.", globalJsonModel.Sdk.Version, globalJsonModel.Sdk.RollForward, globalJsonModel.Sdk.AllowPreRelease); sdkVersion = GetSatisfyingSdkVersion(globalJsonModel, availableSdks); } return(sdkVersion); }
public void ChangeVersionExceptions() { // Callbacks bool configCalled = false; void Handler_OnConfigVersionChanged(PackageHandler arg1, Config config, SemVer.Version arg2) { configCalled = true; } bool called = false; void Handler_OnVersionChanged(PackageHandler arg1, SemVer.Version arg2) { called = true; } var config = new Config { Info = new PackageInfo("N", "ID", new SemVer.Version("0.0.1")) }; var configProvider = Utils.GetConfigProvider(config, failToGet: true); var handler = new PackageHandler(configProvider.Object); handler.OnConfigVersionChanged += Handler_OnConfigVersionChanged; handler.OnVersionChanged += Handler_OnVersionChanged; // Should throw an ANE for a null version Assert.Throws <ArgumentNullException>(() => handler.ChangeVersion(null)); // Should throw a failure if the config could not be found var newVersion = new SemVer.Version("0.1.0"); Assert.Throws <ConfigException>(() => handler.ChangeVersion(newVersion)); // Config should never have been committed or changed configProvider.Verify(mocks => mocks.Commit(), Times.Never); Assert.False(config.Info.Version == newVersion); // Callbacks should never have been called Assert.False(configCalled); Assert.False(called); config = new Config(); configProvider = Utils.GetConfigProvider(config); handler = new PackageHandler(configProvider.Object); handler.OnConfigVersionChanged += Handler_OnConfigVersionChanged; handler.OnVersionChanged += Handler_OnVersionChanged; // Should throw a failure if the config.Info property is null Assert.Throws <ConfigException>(() => handler.ChangeVersion(newVersion)); // Config should never have been committed configProvider.Verify(mocks => mocks.Commit(), Times.Never); // Callbacks should never have been called Assert.False(configCalled); Assert.False(called); }
public Version(int major, int minor, int patch, string preRelease = null, string build = null) { var version = new SemVer.Version(major, minor, patch, preRelease, build); this.Major = version.Major; this.Minor = version.Minor; this.Patch = version.Patch; this.PreRelease = version.PreRelease; this.Build = version.Build; }
public void Init(IPALogger logger, PluginMetadata metadata) { Logger.log = logger; Configuration.Init(); if (metadata?.Version != null) { PluginVersion = metadata.Version; } }
public void Init(IPALogger logger, [Config.Prefer("json")] IConfigProvider cfgProvider, PluginLoader.PluginMetadata metadata) { Logger.log = logger; Configuration.Init(cfgProvider); if (metadata != null) { PluginVersion = metadata.Version; } }
public void Init(IPALogger log, PluginLoader.PluginMetadata metadata) { Logger = log; if (metadata != null) { PluginVersion = metadata.Version; Log("Version number set"); } }
public Version(string input) { var version = new SemVer.Version(input, true); this.Major = version.Major; this.Minor = version.Minor; this.Patch = version.Patch; this.PreRelease = version.PreRelease; this.Build = version.Build; }
internal Artifact(Product product, Version version, SnapshotApiResolver.SearchPackage package, string buildHash = null) { ProductName = product.ProductName; Version = version; State = ArtifactBuildState.Snapshot; DownloadUrl = product?.PatchDownloadUrl(package.DownloadUrl); ShaUrl = package.ShaUrl; AscUrl = package.AscUrl; BuildHash = buildHash; }
private void OnExecute() { // Create updated version // Throws on failure var newVersion = new SemVer.Version(Version); // Call package handler change version Program.PackageHandler.ChangeVersion(newVersion); Console.WriteLine($"Changed version of package to: {newVersion} ok!"); Utils.WriteSuccess(); }
private async Task <PackageInfo> GetPackageInfoByStringAsync(string packageId, string packageVersionValue, bool preReleased, string repository) { PackageInfo package = null; // if packageVersionValue is null, get the newest version if (packageVersionValue == null || packageVersionValue == "") { PackageOption option = new PackageOption() { packageId = packageId, includePrerelease = preReleased, registry = repository }; IEnumerable <string> versionList = await GetPackageVersionAsync(option.packageId, option.registry, option.includePrerelease); if (versionList != null) { packageVersionValue = versionList.ElementAt(0); } else { return(null); } } SemVer.Version packageVersion = null; SemVer.Range range = null; if (SemVer.Version.TryParse(packageVersionValue, out packageVersion) == true) { // version Console.WriteLine($"Convet to version: {packageId}: {packageVersionValue}"); package = new PackageInfo { packageId = packageId, packageVersion = packageVersion }; } else if (SemVer.Range.TryParse(packageVersionValue, out range)) { // range Console.WriteLine($"Convet to range: {packageId}: {packageVersionValue}"); package = await GetBestMatchPackageVersionsAsync(repository, preReleased, packageId, range); Console.WriteLine($"Find best match: {packageId}: {package?.packageVersion?.ToString()}"); } else { // range of * Console.WriteLine($"Convet to range: {packageId}: {packageVersionValue}"); range = new SemVer.Range("*"); package = await GetBestMatchPackageVersionsAsync(repository, preReleased, packageId, range); Console.WriteLine($"Find best match: {packageId}: {package?.packageVersion?.ToString()}"); } return(package); }
static VersionUtil() { Version?assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version; if (assemblyVersion == null) { throw new NullReferenceException("Assembly version was null, unable to get version of QuestPatcher"); } QuestPatcherVersion = new SemVer.Version(assemblyVersion.Major, assemblyVersion.Minor, assemblyVersion.Build); }
/// <summary> /// Compares a pair of <see cref="SemVer.Version"/>s ignoring both the prerelease and build fields. /// </summary> /// <param name="l">the left value</param> /// <param name="r">the right value</param> /// <returns>< 0 if l is less than r, 0 if they are equal in the numeric portion, or > 0 if l is greater than r</returns> public static int VersionCompareNoPrerelease(SemVer.Version l, SemVer.Version r) { var cmpVal = l.Major - r.Major; if (cmpVal != 0) { return(cmpVal); } cmpVal = l.Minor - r.Minor; if (cmpVal != 0) return(cmpVal); }
public override JsonElement?GetVersionElement(JsonDocument contentJSON, Version version) { try { var versionElement = contentJSON.RootElement.GetProperty("releases").GetProperty(version.ToString()); return(versionElement); } catch (KeyNotFoundException) { return(null); } }
private static void PackageHandler_OnVersionChanged(PackageHandler handler, SemVer.Version version) { // Perform Android.mk, c_cpp_properties.json, bmbfmod.json edits to version var props = propertiesProvider.GetProperties(); if (props != null) { props.UpdateVersion(version); propertiesProvider.SerializeProperties(props); } var mod = bmbfmodProvider.GetMod(); if (mod != null) { mod.UpdateVersion(version); bmbfmodProvider.SerializeMod(mod); } var conf = configProvider.GetConfig(); if (conf is null) { throw new ConfigException("Config is null!"); } if (conf.Info is null) { throw new ConfigException("Config info is null!"); } if (conf.Info.Id is null) { throw new ConfigException("Config ID is null!"); } bool overrodeName = conf.Info.AdditionalData.TryGetValue(SupportedPropertiesCommand.OverrideSoName, out var overridenName); var mk = androidMkProvider.GetFile(); if (mk != null) { var module = mk.Modules.LastOrDefault(); if (module != null) { module.AddDefine("VERSION", version.ToString()); if (overrodeName) { module.Id = overridenName.GetString().ReplaceFirst("lib", "").ReplaceLast(".so", ""); } else { module.EnsureIdIs(conf.Info.Id, version); } androidMkProvider.SerializeFile(mk); } } }
internal UpdateInfoNode(string JSON) : base(JSON) { ID = GetInt("id"); Version = new Version(GetString("vnr"), true); Title = GetString("title"); Description = GetString("desc").Replace("\\r\\n", "\r\n"); Changelog = GetString("clog").Replace("\\r\\n", "\r\n"); File = GetString("file"); Type = GetEnum <UpdateType>("type"); FileSize = GetLong("size"); PreRelease = GetInt("prerelease") == 1 ? true : false; }
public ChartRelease( Chart chart, SemVer.Version version, string description = null, string home = null, string icon = null) { Chart = chart ?? throw new ArgumentNullException(nameof(chart)); Version = version ?? throw new ArgumentNullException(nameof(version)); Description = description; Home = home; Icon = icon; }
public static void UpdateMod(Mod mod, Version versionNumber) { App.RunInBackgroundThread(() => { List <ModOperation.ModOperation> ops = new(); // Check that the requested version won't cause any issues var notSatisfied = new List <string>(); foreach (var dependents in mod.InstalledDirectDependents) { if (!dependents.Installed.Dependencies[mod.Guid].IsSatisfied(versionNumber)) { notSatisfied.Add(dependents.ToString()); } } foreach ((string key, Range value) in mod.Versions[versionNumber].Dependencies) { var dependency = ModRepository.Instance.Mods[key]; // If for some reason the user doesn't have a dependency installed, skip this because it will be installed later. if (!dependency.IsInstalled) { continue; } if (!value.IsSatisfied(dependency.InstalledVersion)) { notSatisfied.Add(dependency.ToString()); } } if (notSatisfied.Count == 0) { ExecuteOperations(EnumerateInstallDependencies(mod, versionNumber).Concat(new ModOperation.ModOperation[] { new UninstallModOperation(mod), new InstallModOperation(mod, versionNumber) })); } else { App.RunInMainThread(() => { string op = mod.InstalledVersion < versionNumber ? "updated" : "downgraded"; var dialogue = new AlertDialogue("Error", $"This mod cannot be {op} because one or more installed mods are not compatible with the selected version:\n" + string.Join(", ", notSatisfied)); App.Current.QueueDialog(dialogue); }); } }); }
private void ModRepositoryUpdated() { var applicationData = ModRepository.Instance.ApplicationData; var cVer = Version.Parse($"{ThisAssembly.Git.SemVer.Major}.{ThisAssembly.Git.SemVer.Minor}.{ThisAssembly.Git.SemVer.Patch}"); if (applicationData != null && applicationData.LatestApplicationVersion > cVer) { App.RunInMainThread(() => { UpdateText.Visibility = Visibility.Visible; UpdateText.Text = $"Update to {applicationData.LatestApplicationVersion} available!\n{applicationData.UpdateText}"; }); } }
/// <summary> /// Check if this version is compatible agains an starcounter version /// </summary> /// <param name="starcounterVersion"></param> /// <returns></returns> public bool IsCompatibleWith(string versionCompability) { if (string.IsNullOrEmpty(versionCompability)) { return true; } try { SemVer.Version scVersion = new SemVer.Version(this.StarcounterVersion, true); SemVer.Range versionRange = new SemVer.Range(versionCompability, true); return ((versionRange == null || scVersion == null) || versionRange.IsSatisfied(this.StarcounterVersion, true)); } catch (Exception) { return false; } }