コード例 #1
0
            public override object ReadJson(
                JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer
                )
            {
                if (reader.Value == null)
                {
                    return(null);
                }

                string raw_version = reader.Value.ToString();

                return(KspVersion.Parse(Regex.Replace(raw_version, @"-.*$", "")));
            }
コード例 #2
0
        private void LoadCompatibleVersions()
        {
            String path = CompatibleKspVersionsFile();

            if (File.Exists(path))
            {
                string json = File.ReadAllText(path);
                CompatibleKspVersionsDto compatibleKspVersionsDto = JsonConvert.DeserializeObject <CompatibleKspVersionsDto>(json);

                _compatibleVersions = compatibleKspVersionsDto.CompatibleKspVersions.Select(v => KspVersion.Parse(v)).ToList();
                this.VersionOfKspWhenCompatibleVersionsWereStored = KspVersion.Parse(compatibleKspVersionsDto.VersionOfKspWhenWritten);
            }
        }
コード例 #3
0
        public void GenerallySafeStrict(Type type, bool expected)
        {
            var comparator = (CKAN.IGameComparator)Activator.CreateInstance(type);

            // We're going to tweak compatibly to mark the mod as being for 1.0.3 ONLY
            gameMod.ksp_version = gameMod.ksp_version_min = gameMod.ksp_version_max
                                                                = KspVersion.Parse("1.0.3");

            gameMod.ksp_version_strict = true;

            // Now test!
            Assert.AreEqual(expected, comparator.Compatible(new KspVersionCriteria(gameVersion), gameMod));
        }
コード例 #4
0
        public void FakeInstance_InvalidVersion_ThrowsBadKSPVersionKraken()
        {
            string     name    = "testname";
            string     tempdir = TestData.NewTempDir();
            KspVersion version = KspVersion.Parse("1.1.99");

            Assert.Throws <BadKSPVersionKraken>(() =>
                                                manager.FakeInstance(name, tempdir, version));
            Assert.IsFalse(manager.HasInstance(name));

            // Tidy up.
            System.IO.Directory.Delete(tempdir, true);
        }
コード例 #5
0
            public override object ReadJson(
                JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer
                )
            {
                if (reader.Value == null)
                {
                    return(null);
                }

                string raw_version = reader.Value.ToString();

                return(KspVersion.Parse(ExpandVersionIfNeeded(raw_version)));
            }
コード例 #6
0
        public void FakeInstance_InNotEmptyFolder_ThrowsBadInstallLocationKraken()
        {
            string     name    = "testname";
            string     tempdir = TestData.NewTempDir();
            KspVersion version = KspVersion.Parse("1.5.1");

            System.IO.File.Create(System.IO.Path.Combine(tempdir, "shouldntbehere.txt")).Close();

            Assert.Throws <BadInstallLocationKraken>(() =>
                                                     manager.FakeInstance(name, tempdir, version));
            Assert.IsFalse(manager.HasInstance(name));

            // Tidy up.
            System.IO.Directory.Delete(tempdir, true);
        }
コード例 #7
0
ファイル: RelationshipResolver.cs プロジェクト: yalov/CKAN
        public void Constructor_WithRegistryThatHasRequiredModuleRemoved_Throws()
        {
            var list = new List <string>();
            var mod  = generator.GeneratorRandomModule();

            mod.ksp_version = KspVersion.Parse("0.10");
            list.Add(mod.identifier);
            registry.AddAvailable(mod);
            registry.RemoveAvailable(mod);

            Assert.Throws <ModuleNotFoundKraken>(() => new RelationshipResolver(
                                                     list,
                                                     options,
                                                     registry,
                                                     null));
        }
コード例 #8
0
 private void AddVersionToListButton_Click(object sender, System.EventArgs e)
 {
     if (AddVersionToListTextBox.Text.Length == 0)
     {
         return;
     }
     try
     {
         var version = KspVersion.Parse(AddVersionToListTextBox.Text);
         SelectedVersionsCheckedListBox.Items.Insert(0, version);
     }
     catch (FormatException)
     {
         MessageBox.Show("Version has invalid format", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
コード例 #9
0
        private bool TryFieldsToModule(out string error, out Control badField)
        {
            if (!Identifier.ValidIdentifierPattern.IsMatch(IdentifierTextBox.Text))
            {
                error    = Properties.Resources.EditModpackBadIdentifier;
                badField = IdentifierTextBox;
                return(false);
            }
            if (string.IsNullOrEmpty(NameTextBox.Text))
            {
                error    = Properties.Resources.EditModpackBadName;
                badField = NameTextBox;
                return(false);
            }
            if (string.IsNullOrEmpty(VersionTextBox.Text))
            {
                error    = Properties.Resources.EditModpackBadVersion;
                badField = VersionTextBox;
                return(false);
            }
            if (!string.IsNullOrEmpty(KspVersionMinComboBox.Text) && !string.IsNullOrEmpty(KspVersionMaxComboBox.Text) &&
                KspVersion.Parse(KspVersionMinComboBox.Text) > KspVersion.Parse(KspVersionMaxComboBox.Text))
            {
                error    = Properties.Resources.EditModpackBadKspVersions;
                badField = KspVersionMinComboBox;
                return(false);
            }

            error             = null;
            badField          = null;
            module.identifier = IdentifierTextBox.Text;
            module.name       = NameTextBox.Text;
            module.@abstract  = AbstractTextBox.Text;
            module.version    = new ModuleVersion(VersionTextBox.Text);
            module.license    = new List <License>()
            {
                new License(LicenseComboBox.Text)
            };
            module.ksp_version_min = string.IsNullOrEmpty(KspVersionMinComboBox.Text)
                ? null
                : KspVersion.Parse(KspVersionMinComboBox.Text);
            module.ksp_version_max = string.IsNullOrEmpty(KspVersionMaxComboBox.Text)
                ? null
                : KspVersion.Parse(KspVersionMaxComboBox.Text);
            return(true);
        }
コード例 #10
0
ファイル: StagingTransformer.cs プロジェクト: waralper1/CKAN
        private bool VersionsNeedManualReview(Metadata metadata, out string reason)
        {
            JObject json   = metadata.Json();
            var     minStr = json["ksp_version_min"] ?? json["ksp_version"];
            var     maxStr = json["ksp_version_max"] ?? json["ksp_version"];
            var     minVer = minStr == null ? KspVersion.Any : KspVersion.Parse((string)minStr);
            var     maxVer = maxStr == null ? KspVersion.Any : KspVersion.Parse((string)maxStr);

            if (currentRelease.IntersectWith(new KspVersionRange(minVer, maxVer)) == null)
            {
                reason = $"Hard-coded game versions not compatible with current release: {KspVersionRange.VersionSpan(minVer, maxVer)}\r\nPlease check that they match the forum thread.";
                return(true);
            }
            else
            {
                // Compatible with latest release, no manual review needed
                reason = "";
                return(false);
            }
        }
コード例 #11
0
 public override object ReadJson(
     JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer
     )
 {
     if (reader.TokenType == JsonToken.StartArray)
     {
         return(JArray.Load(reader)
                .Values <string>()
                .Select(v => KspVersion.Parse(Regex.Replace(v, @"-.*$", "")))
                .ToArray());
     }
     else
     {
         if (reader.Value == null)
         {
             return(null);
         }
         string raw_version = reader.Value.ToString();
         return(KspVersion.Parse(Regex.Replace(raw_version, @"-.*$", "")));
     }
 }
コード例 #12
0
ファイル: RelationshipResolver.cs プロジェクト: yalov/CKAN
        public void AutodetectedCanSatisfyRelationships()
        {
            using (var ksp = new DisposableKSP())
            {
                registry.RegisterDll(ksp.KSP, Path.Combine(ksp.KSP.GameData(), "ModuleManager.dll"));

                var depends = new List <CKAN.RelationshipDescriptor>();
                depends.Add(new CKAN.RelationshipDescriptor {
                    name = "ModuleManager"
                });

                CkanModule mod = generator.GeneratorRandomModule(depends: depends);

                new RelationshipResolver(
                    new CkanModule[] { mod },
                    RelationshipResolver.DefaultOpts(),
                    registry,
                    new KspVersionCriteria(KspVersion.Parse("1.0.0"))
                    );
            }
        }
コード例 #13
0
        public bool TryGetVersion(string directory, out KspVersion result)
        {
            var readmePath = Path.Combine(directory, "readme.txt");

            if (File.Exists(readmePath))
            {
                var match = File
                            .ReadAllLines(readmePath)
                            .Select(i => VersionPattern.Match(i))
                            .FirstOrDefault(i => i.Success);

                if (match != null)
                {
                    result = KspVersion.Parse(match.Groups["version"].Value);
                    return(true);
                }
            }

            result = default(KspVersion);
            return(false);
        }
コード例 #14
0
        public void FakeInstance_DlcsWithWrongBaseVersion_ThrowsWrongKSPVersionKraken(string baseVersion)
        {
            string     name      = "testname";
            KspVersion mhVersion = KspVersion.Parse("1.1.0");
            KspVersion bgVersion = KspVersion.Parse("1.0.0");
            string     tempdir   = TestData.NewTempDir();
            KspVersion version   = KspVersion.Parse(baseVersion);

            Dictionary <CKAN.DLC.IDlcDetector, KspVersion> dlcs = new Dictionary <CKAN.DLC.IDlcDetector, KspVersion>()
            {
                { new CKAN.DLC.MakingHistoryDlcDetector(), mhVersion },
                { new CKAN.DLC.BreakingGroundDlcDetector(), bgVersion }
            };

            Assert.Throws <WrongKSPVersionKraken>(() =>
                                                  manager.FakeInstance(name, tempdir, version, dlcs));
            Assert.IsFalse(manager.HasInstance(name));

            // Tidy up.
            System.IO.Directory.Delete(tempdir, true);
        }
コード例 #15
0
ファイル: AvcTransformerTests.cs プロジェクト: yixi435/CKAN
        public void PreferentiallyAddsRangedKspVersionInfo()
        {
            // Arrange
            var avcVersion = new AvcVersion
            {
                ksp_version     = KspVersion.Parse("1.0.4"),
                ksp_version_min = KspVersion.Parse("0.90"),
                ksp_version_max = KspVersion.Parse("1.0.3")
            };

            var mHttp          = new Mock <IHttpService>();
            var mModuleService = new Mock <IModuleService>();

            mModuleService.Setup(i => i.GetInternalAvc(It.IsAny <CkanModule>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(avcVersion);

            var sut = new AvcTransformer(mHttp.Object, mModuleService.Object);

            var json = new JObject();

            json["spec_version"] = 1;
            json["identifier"]   = "AwesomeMod";
            json["$vref"]        = "#/ckan/ksp-avc";
            json["download"]     = "https://awesomemod.example/AwesomeMod.zip";

            // Act
            var result          = sut.Transform(new Metadata(json), opts).First();
            var transformedJson = result.Json();

            // Assert
            Assert.That((string)transformedJson["ksp_version_min"], Is.EqualTo("0.90"),
                        "AvcTransformer should add the KSP min version specified in the AVC version file."
                        );
            Assert.That((string)transformedJson["ksp_version_max"], Is.EqualTo("1.0.3"),
                        "AvcTransformer should add the KSP min version specified in the AVC version file."
                        );
            Assert.That(transformedJson["ksp_version"], Is.Null,
                        "AvcTransformer should not add a KSP version if min or max versions are specified."
                        );
        }
コード例 #16
0
ファイル: AvcTransformerTests.cs プロジェクト: yixi435/CKAN
        public void CorrectlyCalculatesKspVersionInfo(
            string existingKsp, string existingKspMin, string existingKspMax,
            string avcKsp, string avcKspMin, string avcKspMax,
            string expectedKsp, string expectedKspMin, string expectedKspMax
            )
        {
            // Arrange
            var json = new JObject();

            json["spec_version"] = 1;
            json["identifier"]   = "AwesomeMod";
            json["$vref"]        = "#/ckan/ksp-avc";
            json["download"]     = "https://awesomemod.example/AwesomeMod.zip";

            if (!string.IsNullOrWhiteSpace(existingKsp))
            {
                json["ksp_version"] = existingKsp;
            }

            if (!string.IsNullOrWhiteSpace(existingKspMin))
            {
                json["ksp_version_min"] = existingKspMin;
            }

            if (!string.IsNullOrWhiteSpace(existingKspMax))
            {
                json["ksp_version_max"] = existingKspMax;
            }

            var avcVersion = new AvcVersion();

            if (!string.IsNullOrWhiteSpace(avcKsp))
            {
                avcVersion.ksp_version = KspVersion.Parse(avcKsp);
            }

            if (!string.IsNullOrWhiteSpace(avcKspMin))
            {
                avcVersion.ksp_version_min = KspVersion.Parse(avcKspMin);
            }

            if (!string.IsNullOrWhiteSpace(avcKspMax))
            {
                avcVersion.ksp_version_max = KspVersion.Parse(avcKspMax);
            }

            var mHttp          = new Mock <IHttpService>();
            var mModuleService = new Mock <IModuleService>();

            mModuleService.Setup(i => i.GetInternalAvc(It.IsAny <CkanModule>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(avcVersion);

            var sut = new AvcTransformer(mHttp.Object, mModuleService.Object);

            // Act
            var result          = sut.Transform(new Metadata(json), opts).First();
            var transformedJson = result.Json();

            // Assert
            Assert.That((string)transformedJson["ksp_version"], Is.EqualTo(expectedKsp),
                        "AvcTransformer should calculate ksp_version correctly"
                        );

            Assert.That((string)transformedJson["ksp_version_min"], Is.EqualTo(expectedKspMin),
                        "AvcTransformer should calculate ksp_version_min correctly"
                        );

            Assert.That((string)transformedJson["ksp_version_max"], Is.EqualTo(expectedKspMax),
                        "AvcTransformer should calculate ksp_version_max correctly"
                        );
        }
コード例 #17
0
        public static void ApplyVersions(JObject json, AvcVersion avc)
        {
            // Get the minimum and maximum KSP versions that already exist in the metadata.
            // Use specific KSP version if min/max don't exist.
            var existingKspMinStr = (string)json["ksp_version_min"] ?? (string)json["ksp_version"];
            var existingKspMaxStr = (string)json["ksp_version_max"] ?? (string)json["ksp_version"];

            var existingKspMin = existingKspMinStr == null ? null : KspVersion.Parse(existingKspMinStr);
            var existingKspMax = existingKspMaxStr == null ? null : KspVersion.Parse(existingKspMaxStr);

            // Get the minimum and maximum KSP versions that are in the AVC file.
            // Use specific KSP version if min/max don't exist.
            var avcKspMin = avc.ksp_version_min ?? avc.ksp_version;
            var avcKspMax = avc.ksp_version_max ?? avc.ksp_version;

            // Now calculate the minimum and maximum KSP versions between both the existing metadata and the
            // AVC file.
            var kspMins  = new List <KspVersion>();
            var kspMaxes = new List <KspVersion>();

            if (!KspVersion.IsNullOrAny(existingKspMin))
            {
                kspMins.Add(existingKspMin);
            }

            if (!KspVersion.IsNullOrAny(avcKspMin))
            {
                kspMins.Add(avcKspMin);
            }

            if (!KspVersion.IsNullOrAny(existingKspMax))
            {
                kspMaxes.Add(existingKspMax);
            }

            if (!KspVersion.IsNullOrAny(avcKspMax))
            {
                kspMaxes.Add(avcKspMax);
            }

            var kspMin = kspMins.Any()  ? kspMins.Min()  : null;
            var kspMax = kspMaxes.Any() ? kspMaxes.Max() : null;

            if (kspMin != null || kspMax != null)
            {
                // If we have either a minimum or maximum KSP version, remove all existing KSP version
                // information from the metadata.
                json.Remove("ksp_version");
                json.Remove("ksp_version_min");
                json.Remove("ksp_version_max");

                if (kspMin != null && kspMax != null)
                {
                    // If we have both a minimum and maximum KSP version...
                    if (kspMin.CompareTo(kspMax) == 0)
                    {
                        // ...and they are equal, then just set ksp_version
                        json["ksp_version"] = kspMin.ToString();
                    }
                    else
                    {
                        // ...otherwise set both ksp_version_min and ksp_version_max
                        json["ksp_version_min"] = kspMin.ToString();
                        json["ksp_version_max"] = kspMax.ToString();
                    }
                }
                else
                {
                    // If we have only one or the other then set which ever is applicable

                    if (kspMin != null)
                    {
                        json["ksp_version_min"] = kspMin.ToString();
                    }

                    if (kspMax != null)
                    {
                        json["ksp_version_max"] = kspMax.ToString();
                    }
                }
            }

            if (avc.version != null)
            {
                // In practice, the version specified in .version files tends to be unreliable, with authors
                // forgetting to update it when new versions are released. Therefore if we have a version
                // specified from another source such as SpaceDock, curse or a GitHub tag, don't overwrite it
                // unless x_netkan_trust_version_file is true.
                if ((bool?)json["x_netkan_trust_version_file"] ?? false)
                {
                    json.Remove("version");
                }
                json.SafeAdd("version", avc.version.ToString());
            }
        }
コード例 #18
0
        public void TestStrictGameComparator(String modVersion, String gameVersion, bool expectedResult)
        {
            var comparator = new CKAN.StrictGameComparator();

            // We're going to tweak compatibly of the mod
            gameMod.ksp_version = KspVersion.Parse(modVersion);

            // Now test!
            Assert.AreEqual(expectedResult, comparator.Compatible(new KspVersionCriteria(KspVersion.Parse(gameVersion)), gameMod));
        }
コード例 #19
0
ファイル: AvcTransformer.cs プロジェクト: rbarraud/CKAN
        public static void ApplyVersions(JObject json, AvcVersion avc)
        {
            // Get the minimum and maximum KSP versions that already exist in the metadata.
            // Use specific KSP version if min/max don't exist.
            var existingKspMinStr = (string)json["ksp_version_min"] ?? (string)json["ksp_version"];
            var existingKspMaxStr = (string)json["ksp_version_max"] ?? (string)json["ksp_version"];

            var existingKspMin = existingKspMinStr == null ? null : KspVersion.Parse(existingKspMinStr);
            var existingKspMax = existingKspMaxStr == null ? null : KspVersion.Parse(existingKspMaxStr);

            // Get the minimum and maximum KSP versions that are in the AVC file.
            // http://ksp.cybutek.net/kspavc/Documents/README.htm
            // KSP-AVC allows (requires?) KSP_VERSION to be set
            // when KSP_VERSION_MIN/_MAX are set, but CKAN treats
            // its equivalent properties as mutually exclusive.
            // Only fallback if neither min nor max are defined,
            // for open ranges.
            KspVersion avcKspMin, avcKspMax;

            if (avc.ksp_version_min == null && avc.ksp_version_max == null)
            {
                // Use specific KSP version if min/max don't exist
                avcKspMin = avcKspMax = avc.ksp_version;
            }
            else
            {
                avcKspMin = avc.ksp_version_min;
                avcKspMax = avc.ksp_version_max;
            }

            // Now calculate the minimum and maximum KSP versions between both the existing metadata and the
            // AVC file.
            var kspMins  = new List <KspVersion>();
            var kspMaxes = new List <KspVersion>();

            if (!KspVersion.IsNullOrAny(existingKspMin))
            {
                kspMins.Add(existingKspMin);
            }

            if (!KspVersion.IsNullOrAny(avcKspMin))
            {
                kspMins.Add(avcKspMin);
            }

            if (!KspVersion.IsNullOrAny(existingKspMax))
            {
                kspMaxes.Add(existingKspMax);
            }

            if (!KspVersion.IsNullOrAny(avcKspMax))
            {
                kspMaxes.Add(avcKspMax);
            }

            var kspMin = kspMins.Any()  ? kspMins.Min()  : null;
            var kspMax = kspMaxes.Any() ? kspMaxes.Max() : null;

            if (kspMin != null || kspMax != null)
            {
                // If we have either a minimum or maximum KSP version, remove all existing KSP version
                // information from the metadata.
                json.Remove("ksp_version");
                json.Remove("ksp_version_min");
                json.Remove("ksp_version_max");

                if (kspMin != null && kspMax != null)
                {
                    // If we have both a minimum and maximum KSP version...
                    if (kspMin.CompareTo(kspMax) == 0)
                    {
                        // ...and they are equal, then just set ksp_version
                        json["ksp_version"] = kspMin.ToString();
                    }
                    else
                    {
                        // ...otherwise set both ksp_version_min and ksp_version_max
                        json["ksp_version_min"] = kspMin.ToString();
                        json["ksp_version_max"] = kspMax.ToString();
                    }
                }
                else
                {
                    // If we have only one or the other then set which ever is applicable

                    if (kspMin != null)
                    {
                        json["ksp_version_min"] = kspMin.ToString();
                    }

                    if (kspMax != null)
                    {
                        json["ksp_version_max"] = kspMax.ToString();
                    }
                }
            }

            if (avc.version != null)
            {
                // In practice, the version specified in .version files tends to be unreliable, with authors
                // forgetting to update it when new versions are released. Therefore if we have a version
                // specified from another source such as SpaceDock, curse or a GitHub tag, don't overwrite it
                // unless x_netkan_trust_version_file is true.
                if ((bool?)json["x_netkan_trust_version_file"] ?? false)
                {
                    json.Remove("version");
                }
                json.SafeAdd("version", avc.version.ToString());
            }
        }
コード例 #20
0
ファイル: CkanModule.cs プロジェクト: zakipatel/CKAN
 /// <summary>
 /// Returns true if our mod is compatible with the KSP version specified.
 /// </summary>
 public bool IsCompatibleKSP(string version)
 {
     return(IsCompatibleKSP(KspVersion.Parse(version)));
 }
コード例 #21
0
ファイル: JsonAvcToKspVersion.cs プロジェクト: zilti/CKAN
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            string major = null;
            string minor = null;
            string patch = null;

            var token = JToken.Load(reader);

            Log.DebugFormat("Read Token: {0}, {1}", new object[] { token.Type, token.ToString() });
            switch (token.Type)
            {
            case JTokenType.String:
                var tokenArray = token.ToString().Split('.');

                if (tokenArray.Length > 0)
                {
                    major = tokenArray[0];
                }

                if (tokenArray.Length > 1)
                {
                    minor = tokenArray[1];
                }

                if (tokenArray.Length > 2)
                {
                    patch = tokenArray[2];
                }
                break;

            case JTokenType.Object:
                major = (string)token["MAJOR"];
                minor = (string)token["MINOR"];
                patch = (string)token["PATCH"];
                break;

            default:
                throw new InvalidCastException("Trying to convert non-JSON object to Version object");
            }

            //AVC uses -1 to indicate a wildcard.
            int    integer;
            string version;

            if (major == null || int.TryParse(major, out integer) && integer == AvcWildcard)
            {
                return(KspVersion.Any);
            }
            else if (minor == null || int.TryParse(minor, out integer) && integer == AvcWildcard)
            {
                version = major;
            }
            else if (patch == null || int.TryParse(patch, out integer) && integer == AvcWildcard)
            {
                version = string.Join(".", major, minor);
            }
            else
            {
                version = string.Join(".", major, minor, patch);
            }

            Log.DebugFormat("  extracted version: {0}", version);
            var result = KspVersion.Parse(version);

            Log.DebugFormat("  generated result: {0}", result);
            return(result);
        }
コード例 #22
0
        /// <summary>
        /// User is done. Start cloning or faking, depending on the clicked radio button.
        /// Close the window if everything went right.
        /// </summary>
        private async void buttonOK_Click(object sender, EventArgs e)
        {
            string newName = textBoxNewName.Text;
            string newPath = textBoxNewPath.Text;

            // Do some basic checks.
            if (String.IsNullOrWhiteSpace(newName))
            {
                user.RaiseError(Properties.Resources.CloneFakeKspDialogEnterName);
                return;
            }
            if (String.IsNullOrWhiteSpace(newPath))
            {
                user.RaiseError(Properties.Resources.CloneFakeKspDialogEnterPath);
                return;
            }

            // Show progress bar and deactivate controls.
            progressBar.Style = ProgressBarStyle.Marquee;
            progressBar.Show();
            foreach (Control ctrl in this.Controls)
            {
                ctrl.Enabled = false;
            }

            // Clone the specified instance.
            // Done in a new task to not block the GUI thread.
            if (radioButtonClone.Checked)
            {
                user.RaiseMessage(Properties.Resources.CloneFakeKspDialogCloningInstance);

                try
                {
                    await Task.Run(() =>
                    {
                        KSP instanceToClone = new KSP(textBoxClonePath.Text, "irrelevant", user);

                        if (instanceToClone.Valid)
                        {
                            manager.CloneInstance(instanceToClone, newName, newPath);
                        }
                        else
                        {
                            throw new NotKSPDirKraken(instanceToClone.GameDir());
                        }
                    });
                }
                catch (InstanceNameTakenKraken)
                {
                    user.RaiseError(Properties.Resources.CloneFakeKspDialogNameAlreadyUsed);
                    reactivateDialog();
                    return;
                }
                catch (NotKSPDirKraken kraken)
                {
                    user.RaiseError(string.Format(Properties.Resources.CloneFakeKspDialogInstanceNotValid, kraken.path));
                    reactivateDialog();
                    return;
                }
                catch (PathErrorKraken kraken)
                {
                    user.RaiseError(string.Format(Properties.Resources.CloneFakeKspDialogDestinationNotEmpty, kraken.path));
                    reactivateDialog();
                    return;
                }
                catch (IOException ex)
                {
                    user.RaiseError(string.Format(Properties.Resources.CloneFakeKspDialogCloneFailed, ex.Message));
                    reactivateDialog();
                    return;
                }
                catch (Exception ex)
                {
                    user.RaiseError(string.Format(Properties.Resources.CloneFakeKspDialogCloneFailed, ex.Message));
                    reactivateDialog();
                    return;
                }

                if (checkBoxSetAsDefault.Checked)
                {
                    manager.SetAutoStart(newName);
                }

                if (checkBoxSwitchInstance.Checked)
                {
                    manager.SetCurrentInstance(newName);
                }

                user.RaiseMessage(Properties.Resources.CloneFakeKspDialogSuccessfulClone);

                DialogResult = DialogResult.OK;
                this.Close();
            }

            // Create a new dummy instance.
            // Also in a separate task.
            else if (radioButtonFake.Checked)
            {
                KspVersion kspVersion = KspVersion.Parse(comboBoxKspVersion.Text);

                Dictionary <DLC.IDlcDetector, KspVersion> dlcs = new Dictionary <DLC.IDlcDetector, KspVersion>();
                if (!String.IsNullOrWhiteSpace(textBoxMHDlcVersion.Text) && textBoxMHDlcVersion.Text.ToLower() != "none")
                {
                    if (KspVersion.TryParse(textBoxMHDlcVersion.Text, out KspVersion ver))
                    {
                        dlcs.Add(new DLC.MakingHistoryDlcDetector(), ver);
                    }
                    else
                    {
                        user.RaiseError(Properties.Resources.CloneFakeKspDialogDlcVersionMalformatted, "Making History");
                        reactivateDialog();
                        return;
                    }
                }
                if (!String.IsNullOrWhiteSpace(textBoxBGDlcVersion.Text) && textBoxBGDlcVersion.Text.ToLower() != "none")
                {
                    if (KspVersion.TryParse(textBoxBGDlcVersion.Text, out KspVersion ver))
                    {
                        dlcs.Add(new DLC.BreakingGroundDlcDetector(), ver);
                    }
                    else
                    {
                        user.RaiseError(Properties.Resources.CloneFakeKspDialogDlcVersionMalformatted, "Breaking Ground");
                        reactivateDialog();
                        return;
                    }
                }

                user.RaiseMessage(Properties.Resources.CloneFakeKspDialogCreatingInstance);

                try
                {
                    await Task.Run(() =>
                    {
                        manager.FakeInstance(newName, newPath, kspVersion, dlcs);
                    });
                }
                catch (InstanceNameTakenKraken)
                {
                    user.RaiseError(Properties.Resources.CloneFakeKspDialogNameAlreadyUsed);
                    reactivateDialog();
                    return;
                }
                catch (BadInstallLocationKraken)
                {
                    user.RaiseError(Properties.Resources.CloneFakeKspDialogDestinationNotEmpty, newPath);
                    reactivateDialog();
                    return;
                }
                catch (Exception ex)
                {
                    user.RaiseError(string.Format(Properties.Resources.CloneFakeKspDialogFakeFailed, ex.Message));
                    reactivateDialog();
                    return;
                }

                if (checkBoxSetAsDefault.Checked)
                {
                    manager.SetAutoStart(newName);
                }

                if (checkBoxSwitchInstance.Checked)
                {
                    manager.SetCurrentInstance(newName);
                }

                user.RaiseMessage(Properties.Resources.CloneFakeKspDialogSuccessfulCreate);

                DialogResult = DialogResult.OK;
                this.Close();
            }
        }
コード例 #23
0
        public void TestStrictGameComparatorMinMax(String modMinVersion, String modMaxVersion, String gameVersion, bool expectedResult)
        {
            var comparator = new CKAN.StrictGameComparator();

            gameMod.ksp_version     = null;
            gameMod.ksp_version_min = modMinVersion == null ? null : KspVersion.Parse(modMinVersion);
            gameMod.ksp_version_max = modMaxVersion == null ? null : KspVersion.Parse(modMaxVersion);

            // Now test!
            Assert.AreEqual(expectedResult, comparator.Compatible(new KspVersionCriteria(KspVersion.Parse(gameVersion)), gameMod));
        }
コード例 #24
0
ファイル: KSP.cs プロジェクト: justvova34/CKAN
        private void LoadCompatibleVersions()
        {
            String path = CompatibleKspVersionsFile();

            if (File.Exists(path))
            {
                string json = File.ReadAllText(path);
                CompatibleKspVersionsDto compatibleKspVersionsDto = JsonConvert.DeserializeObject <CompatibleKspVersionsDto>(json);

                _compatibleVersions = compatibleKspVersionsDto.CompatibleKspVersions.Select(v => KspVersion.Parse(v)).ToList();

                // Get version without throwing exceptions for null
                KspVersion mainVer = null;
                KspVersion.TryParse(compatibleKspVersionsDto.VersionOfKspWhenWritten, out mainVer);
                this.VersionOfKspWhenCompatibleVersionsWereStored = mainVer;
            }
        }
コード例 #25
0
ファイル: Repo.cs プロジェクト: zicrog/CKAN
        public void UpdateRegistryZip()
        {
            CKAN.Repo.Update(manager, ksp.KSP, new NullUser(), TestData.TestKANZip());

            // Test we've got an expected module.
            CkanModule far = registry.LatestAvailable("FerramAerospaceResearch", new KspVersionCriteria(KspVersion.Parse("0.25.0")));

            Assert.AreEqual("v0.14.3.2", far.version.ToString());
        }
コード例 #26
0
ファイル: Module.cs プロジェクト: gotmachine/CKAN
        public void CompatibleWith()
        {
            CkanModule module = CkanModule.FromJson(TestData.kOS_014());

            Assert.IsTrue(module.IsCompatibleKSP(new KspVersionCriteria(KspVersion.Parse("0.24.2"))));
        }
コード例 #27
0
 private bool CompatibleWithCurrent(string version)
 {
     return(currentRelease.IntersectWith(KspVersion.Parse(version).ToVersionRange()) != null);
 }
コード例 #28
0
        public Metadata Transform(Metadata metadata)
        {
            if (metadata.Vref != null && metadata.Vref.Source == "ksp-avc")
            {
                var json = metadata.Json();

                Log.InfoFormat("Executing Interal AVC transformation with {0}", metadata.Kref);
                Log.DebugFormat("Input metadata:{0}{1}", Environment.NewLine, json);

                var noVersion = metadata.Version == null;

                if (noVersion)
                {
                    json["version"] = "0"; // TODO: DBB: Dummy version necessary to the next statement doesn't throw
                }

                var mod = CkanModule.FromJson(json.ToString());

                if (noVersion)
                {
                    json.Remove("version");
                }

                var file = _http.DownloadPackage(metadata.Download, metadata.Identifier);
                var avc  = _moduleService.GetInternalAvc(mod, file, metadata.Vref.Id);

                if (avc != null)
                {
                    Log.Info("Found internal AVC version file");

                    if (Uri.IsWellFormedUriString(avc.Url, UriKind.Absolute))
                    {
                        Log.InfoFormat("Found remote AVC version file at {0}", avc.Url);

                        try
                        {
                            var remoteJson = Net.DownloadText(avc.Url);
                            var remoteAvc  = JsonConvert.DeserializeObject <AvcVersion>(remoteJson);

                            if (avc.version.CompareTo(remoteAvc.version) == 0)
                            {
                                // Local AVC and Remote AVC describe the same version, prefer
                                Log.Info("Remote AVC version file describes same version as local AVC version file, using it preferrentially.");
                                avc = remoteAvc;
                            }
                        }
                        catch (Exception e)
                        {
                            Log.InfoFormat("An error occured fetching the remote AVC version file, ignoring: {0}", e.Message);
                            Log.Debug(e);
                        }
                    }

                    // Get the minimum and maximum KSP versions that already exist in the metadata.
                    // Use specific KSP version if min/max don't exist.
                    var existingKspMinStr = (string)json["ksp_version_min"] ?? (string)json["ksp_version"];
                    var existingKspMaxStr = (string)json["ksp_version_max"] ?? (string)json["ksp_version"];

                    var existingKspMin = existingKspMinStr == null ? null : KspVersion.Parse(existingKspMinStr);
                    var existingKspMax = existingKspMaxStr == null ? null : KspVersion.Parse(existingKspMaxStr);

                    // Get the minimum and maximum KSP versions that are in the AVC file.
                    // Use specific KSP version if min/max don't exist.
                    var avcKspMin = avc.ksp_version_min ?? avc.ksp_version;
                    var avcKspMax = avc.ksp_version_max ?? avc.ksp_version;

                    // Now calculate the minimum and maximum KSP versions between both the existing metadata and the
                    // AVC file.
                    var kspMins  = new List <KspVersion>();
                    var kspMaxes = new List <KspVersion>();

                    if (existingKspMin != null)
                    {
                        kspMins.Add(existingKspMin);
                    }

                    if (avcKspMin != null)
                    {
                        kspMins.Add(avcKspMin);
                    }

                    if (existingKspMax != null)
                    {
                        kspMaxes.Add(existingKspMax);
                    }

                    if (avcKspMax != null)
                    {
                        kspMaxes.Add(avcKspMax);
                    }

                    var kspMin = kspMins.Any() ? kspMins.Min() : null;
                    var kspMax = kspMaxes.Any() ? kspMaxes.Max() : null;

                    if (kspMin != null || kspMax != null)
                    {
                        // If we have either a minimum or maximum KSP version, remove all existing KSP version
                        // information from the metadata.
                        json.Remove("ksp_version");
                        json.Remove("ksp_version_min");
                        json.Remove("ksp_version_max");

                        if (kspMin != null && kspMax != null)
                        {
                            // If we have both a minimum and maximum KSP version...
                            if (kspMin.CompareTo(kspMax) == 0)
                            {
                                // ...and they are equal, then just set ksp_version
                                json["ksp_version"] = kspMin.ToString();
                            }
                            else
                            {
                                // ...otherwise set both ksp_version_min and ksp_version_max
                                json["ksp_version_min"] = kspMin.ToString();
                                json["ksp_version_max"] = kspMax.ToString();
                            }
                        }
                        else
                        {
                            // If we have only one or the other then set which ever is applicable

                            if (kspMin != null)
                            {
                                json["ksp_version_min"] = kspMin.ToString();
                            }

                            if (kspMax != null)
                            {
                                json["ksp_version_max"] = kspMax.ToString();
                            }
                        }
                    }

                    if (avc.version != null)
                    {
                        // In practice, the version specified in .version files tends to be unreliable, with authors
                        // forgetting to update it when new versions are released. Therefore if we have a version
                        // specified from another source such as SpaceDock or a GitHub tag, don't overwrite it.
                        json.SafeAdd("version", avc.version.ToString());
                    }

                    // It's cool if we don't have version info at all, it's optional in the AVC spec.

                    Log.DebugFormat("Transformed metadata:{0}{1}", Environment.NewLine, json);
                }

                return(new Metadata(json));
            }
            else
            {
                return(metadata);
            }
        }