コード例 #1
0
ファイル: TestData.cs プロジェクト: KSP-CKAN/CKAN
 public CkanModule GeneratorRandomModule(
     KspVersion ksp_version = null,
     List<RelationshipDescriptor> conflicts = null,
     List<RelationshipDescriptor> depends = null,
     List<RelationshipDescriptor> sugests = null,
     List<String> provides = null,
     string identifier = null,
     Version version = null)
 {
     var mod = new CkanModule
     {
         name = Generator.Next().ToString(CultureInfo.InvariantCulture),
         @abstract = Generator.Next().ToString(CultureInfo.InvariantCulture),
         identifier = identifier??Generator.Next().ToString(CultureInfo.InvariantCulture),
         spec_version = new Version(1.ToString(CultureInfo.InvariantCulture)),
         ksp_version = ksp_version ?? KspVersion.Parse("0." + Generator.Next()),
         version = version ?? new Version(Generator.Next().ToString(CultureInfo.InvariantCulture))
     };
     mod.ksp_version_max = mod.ksp_version_min = null;
     mod.conflicts = conflicts;
     mod.depends = depends;
     mod.suggests = sugests;
     mod.provides = provides;
     return mod;
 }
コード例 #2
0
ファイル: KspVersion.cs プロジェクト: zakipatel/CKAN
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var value = reader.Value == null ? null : reader.Value.ToString();

            switch (value)
            {
            case null:
                return(null);

            case "any":
                return(KspVersion.Any);

            default:
                KspVersion result;

                // For a little while, AVC files which didn't specify a full three-part
                // version number could result in versions like `1.1.`, which cause our
                // code to fail. Here we strip any trailing dot from the version number,
                // which makes them valid again before parsing. CKAN#1780

                value = Regex.Replace(value, @"\.$", "");

                if (KspVersion.TryParse(value, out result))
                {
                    return(result);
                }
                else
                {
                    throw new JsonException(string.Format("Could not parse KSP version: {0}", value));
                }
            }
        }
コード例 #3
0
 public KspVersionCriteria(KspVersion v)
 {
     if (v != null)
     {
         this._versions.Add(v);
     }
 }
コード例 #4
0
 /// <summary>
 /// Generate a string describing a range of KSP versions.
 /// May be bounded or unbounded on either side.
 /// </summary>
 /// <param name="minKsp">Lowest version in the range</param>
 /// <param name="maxKsp">Highest version in the range</param>
 /// <returns>
 /// Human readable string describing the versions.
 /// </returns>
 public static string VersionSpan(KspVersion minKsp, KspVersion maxKsp)
 {
     return(minKsp == maxKsp ? $"KSP {SameVersionString(minKsp)}"
         :  minKsp.IsAny     ? $"KSP {maxKsp} and earlier"
         :  maxKsp.IsAny     ? $"KSP {minKsp} and later"
         :                     $"KSP {minKsp} - {maxKsp}");
 }
コード例 #5
0
        public void ReadJsonWorksCorrectly(string json, KspVersion expected)
        {
            // Act
            var result = JsonConvert.DeserializeObject<TestPoco>(json);

            // Assert
            Assert.That(result.KspVersion, Is.EqualTo(expected));
        }
コード例 #6
0
ファイル: RelationshipResolver.cs プロジェクト: Zor-X-L/CKAN
 /// <summary>
 /// Attempts to convert the module_names to ckan modules via  CkanModule.FromIDandVersion and then calls RelationshipResolver.ctor(IEnumerable{CkanModule}, Registry, KSPVersion)"/>
 /// </summary>
 /// <param name="module_names"></param>
 /// <param name="options"></param>
 /// <param name="registry"></param>
 /// <param name="kspversion"></param>
 public RelationshipResolver(IEnumerable<string> module_names, RelationshipResolverOptions options, IRegistryQuerier registry,
     KspVersion kspversion)
     : this(module_names.Select(name => CkanModule.FromIDandVersion(registry, name, kspversion)).ToList(),
             options,
             registry,
             kspversion)
 {
     // Does nothing, just calls the other overloaded constructor
 }
コード例 #7
0
 public KspVersionCriteria(KspVersion v, List <KspVersion> compatibleVersions)
 {
     if (v != null)
     {
         this._versions.Add(v);
     }
     this._versions.AddRange(compatibleVersions);
     this._versions = this._versions.Distinct().ToList();
 }
コード例 #8
0
ファイル: GrasGameComparator.cs プロジェクト: KSP-CKAN/CKAN
        public override bool SingleVersionsCompatible(KspVersion gameVersion, CkanModule module)
        {
            // Otherwise, check if it's "generally recognise as safe".

            // If we're running KSP 1.0.4, then allow the mod to run if we would have
            // considered it compatible under 1.0.3 (as 1.0.4 was "just a hotfix").
            if (gameVersion.Equals (KspVersion.Parse ("1.0.4")))
                return strict.SingleVersionsCompatible (v103, module);

            return false;
        }
コード例 #9
0
        public void WriteJsonWorksCorrectly(KspVersion version, string expected)
        {
            // Arrange
            var poco = new TestPoco { KspVersion = version };

            // Act
            dynamic result = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(poco));

            // Assert
            Assert.That((string)result.KspVersion, Is.EqualTo(expected));
        }
コード例 #10
0
ファイル: RelationshipResolver.cs プロジェクト: Zor-X-L/CKAN
        /// <summary>
        /// Creates a new Relationship resolver.
        /// </summary>
        /// <param name="options"><see cref="RelationshipResolverOptions"/></param>
        /// <param name="registry">The registry to use</param>
        /// <param name="kspversion">The version of the install that the registry corresponds to</param>
        public RelationshipResolver(RelationshipResolverOptions options, IRegistryQuerier registry, KspVersion kspversion)
        {
            this.registry = registry;
            this.kspversion = kspversion;
            this.options = options;

            installed_modules = new HashSet<CkanModule>(registry.InstalledModules.Select(i_module => i_module.Module));
            var installed_relationship = new SelectionReason.Installed();
            foreach (var module in installed_modules)
            {
                reasons.Add(module, installed_relationship);
            }
        }
コード例 #11
0
ファイル: KspVersionBound.cs プロジェクト: Zor-X-L/CKAN
        public KspVersionBound(KspVersion value, bool inclusive)
        {
            if (ReferenceEquals(value, null))
                throw new ArgumentNullException("value");

            if (!value.IsAny && !value.IsFullyDefined)
                throw new ArgumentException("Version must be either fully undefined or fully defined.", "value");

            Value = value;
            Inclusive = inclusive;

            // Workaround an issue in old (<=3.2.x) versions of Mono that does not correctly handle null values
            // returned from ToString().
            var valueStr = value.ToString() ?? string.Empty;

            _string = inclusive ? string.Format("[{0}]", valueStr) : string.Format("({0})", valueStr);
        }
コード例 #12
0
ファイル: StrictGameComparator.cs プロジェクト: KSP-CKAN/CKAN
        public override bool SingleVersionsCompatible(KspVersion gameVersion, CkanModule module)
        {
            var gameVersionRange = gameVersion.ToVersionRange();

            var moduleRange = KspVersionRange.Any;

            if (module.ksp_version != null)
            {
                moduleRange = module.ksp_version.ToVersionRange();
            }
            else if (module.ksp_version_min != null || module.ksp_version_max != null)
            {
                if (module.ksp_version_min != null && module.ksp_version_max != null)
                {
                    if (module.ksp_version_min <= module.ksp_version_max)
                    {
                        var minRange = module.ksp_version_min.ToVersionRange();
                        var maxRange = module.ksp_version_max.ToVersionRange();

                        moduleRange = new KspVersionRange(minRange.Lower, maxRange.Upper);
                    }
                    else
                    {
                        return false;
                    }
                }
                else if (module.ksp_version_min != null)
                {
                    var minRange = module.ksp_version_min.ToVersionRange();

                    moduleRange = new KspVersionRange(minRange.Lower, KspVersionBound.Unbounded);
                }
                else if (module.ksp_version_max != null)
                {
                    var maxRange = module.ksp_version_max.ToVersionRange();

                    moduleRange = new KspVersionRange(KspVersionBound.Unbounded, maxRange.Upper);
                }
            }
            else
            {
                return true;
            }

            return gameVersionRange.IntersectWith(moduleRange) != null;
        }
コード例 #13
0
        public bool Compatible(KspVersion gameVersion, CkanModule module)
        {
            var gameVersionRange = gameVersion.ToVersionRange();

            var moduleRange = KspVersionRange.Any;

            if (module.ksp_version != null)
            {
                moduleRange = module.ksp_version.ToVersionRange();
            }
            else if (module.ksp_version_min != null || module.ksp_version_max != null)
            {
                if (module.ksp_version_min != null && module.ksp_version_max != null)
                {
                    if (module.ksp_version_min <= module.ksp_version_max)
                    {
                        var minRange = module.ksp_version_min.ToVersionRange();
                        var maxRange = module.ksp_version_max.ToVersionRange();

                        moduleRange = new KspVersionRange(minRange.Lower, maxRange.Upper);
                    }
                    else
                    {
                        return false;
                    }
                }
                else if (module.ksp_version_min != null)
                {
                    var minRange = module.ksp_version_min.ToVersionRange();

                    moduleRange = new KspVersionRange(minRange.Lower, KspVersionBound.Unbounded);
                }
                else if (module.ksp_version_max != null)
                {
                    var maxRange = module.ksp_version_max.ToVersionRange();

                    moduleRange = new KspVersionRange(KspVersionBound.Unbounded, maxRange.Upper);
                }
            }
            else
            {
                return true;
            }

            return moduleRange.IsSupersetOf(gameVersionRange);
        }
コード例 #14
0
ファイル: KspVersionBound.cs プロジェクト: airminer/CKAN
        public KspVersionBound(KspVersion value, bool inclusive)
        {
            if (ReferenceEquals(value, null))
            {
                throw new ArgumentNullException("value");
            }

            if (!value.IsAny && !value.IsFullyDefined)
            {
                throw new ArgumentException("Version must be either fully undefined or fully defined.", "value");
            }

            Value     = value;
            Inclusive = inclusive;

            _string = inclusive ? string.Format("[{0}]", value) : string.Format("({0})", value);
        }
コード例 #15
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;
        }
コード例 #16
0
        public KspVersionBound(KspVersion value, bool inclusive)
        {
            if (ReferenceEquals(value, null))
            {
                throw new ArgumentNullException("value");
            }

            if (!value.IsAny && !value.IsFullyDefined)
            {
                throw new ArgumentException("Version must be either fully undefined or fully defined.", "value");
            }

            Value     = value;
            Inclusive = inclusive;

            // Workaround an issue in old (<=3.2.x) versions of Mono that does not correctly handle null values
            // returned from ToString().
            var valueStr = value.ToString() ?? string.Empty;

            _string = inclusive ? string.Format("[{0}]", valueStr) : string.Format("({0})", valueStr);
        }
コード例 #17
0
        public bool TryGetVersion(string directory, out KspVersion result)
        {
            KspVersion buildIdVersion;
            var hasBuildId = TryGetVersionFromFile(Path.Combine(directory, "buildID.txt"), out buildIdVersion);

            KspVersion buildId64Version;
            var hasBuildId64 = TryGetVersionFromFile(Path.Combine(directory, "buildID64.txt"), out buildId64Version);

            if (hasBuildId && hasBuildId64)
            {
                result = KspVersion.Max(buildIdVersion, buildId64Version);

                if (buildIdVersion != buildId64Version)
                {
                    Log.WarnFormat(
                        "Found different KSP versions in buildID.txt ({0}) and buildID64.txt ({1}), assuming {2}.",
                        buildIdVersion,
                        buildId64Version,
                        result
                    );
                }

                return true;
            }
            else if (hasBuildId64)
            {
                result = buildId64Version;
                return true;
            }
            else if (hasBuildId)
            {
                result = buildIdVersion;
                return true;
            }
            else
            {
                result = default(KspVersion);
                return false;
            }
        }
コード例 #18
0
ファイル: KspVersion.cs プロジェクト: airminer/CKAN
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var value = reader.Value == null ? null : reader.Value.ToString();

            switch (value)
            {
            case null:
                return(null);

            case "any":
                return(KspVersion.Any);

            default:
                KspVersion result;
                if (KspVersion.TryParse(value, out result))
                {
                    return(result);
                }
                else
                {
                    throw new JsonException(string.Format("Could not parse KSP version: {0}", value));
                }
            }
        }
コード例 #19
0
        private bool TryGetVersionFromFile(string file, out KspVersion result)
        {
            if (File.Exists(file))
            {
                var match = File
                    .ReadAllLines(file)
                    .Select(i => BuildIdPattern.Match(i))
                    .FirstOrDefault(i => i.Success);

                if (match != null)
                {
                    var version = _kspBuildMap[match.Groups["buildid"].Value];

                    if (version != null)
                    {
                        result = version;
                        return true;
                    }
                }
            }

            result = default(KspVersion);
            return false;
        }
コード例 #20
0
ファイル: Registry.cs プロジェクト: CliftonMarien/CKAN
        /// <summary>
        /// <see cref = "IRegistryQuerier.LatestAvailable" />
        /// </summary>
        // TODO: Consider making this internal, because practically everything should
        // be calling LatestAvailableWithProvides()
        public CkanModule LatestAvailable(
            string module,
            KspVersion ksp_version,
            RelationshipDescriptor relationship_descriptor =null)
        {
            log.DebugFormat("Finding latest available for {0}", module);

            // TODO: Check user's stability tolerance (stable, unstable, testing, etc)

            try
            {
                return available_modules[module].Latest(ksp_version,relationship_descriptor);
            }
            catch (KeyNotFoundException)
            {
                throw new ModuleNotFoundKraken(module);
            }
        }
コード例 #21
0
ファイル: KspVersionTests.cs プロジェクト: Zor-X-L/CKAN
        public void SingleParameterCtorWorksCorrectly()
        {
            // Act
            var result = new KspVersion(1);

            // Assert
            Assert.AreEqual(1, result.Major);
            Assert.AreEqual(-1, result.Minor);
            Assert.AreEqual(-1, result.Patch);
            Assert.AreEqual(-1, result.Build);

            Assert.IsTrue(result.IsMajorDefined);
            Assert.IsFalse(result.IsMinorDefined);
            Assert.IsFalse(result.IsPatchDefined);
            Assert.IsFalse(result.IsBuildDefined);

            Assert.IsFalse(result.IsFullyDefined);
            Assert.IsFalse(result.IsAny);

            Assert.AreEqual("1", result.ToString());
        }
コード例 #22
0
ファイル: KspVersionTests.cs プロジェクト: Zor-X-L/CKAN
        public void QuadrupleParameterCtorWorksCorrectly()
        {
            // Act
            var result = new KspVersion(1, 2, 3, 4);

            // Assert
            Assert.AreEqual(1, result.Major);
            Assert.AreEqual(2, result.Minor);
            Assert.AreEqual(3, result.Patch);
            Assert.AreEqual(4, result.Build);

            Assert.IsTrue(result.IsMajorDefined);
            Assert.IsTrue(result.IsMinorDefined);
            Assert.IsTrue(result.IsPatchDefined);
            Assert.IsTrue(result.IsBuildDefined);

            Assert.IsTrue(result.IsFullyDefined);
            Assert.IsFalse(result.IsAny);

            Assert.AreEqual("1.2.3.4", result.ToString());
        }
コード例 #23
0
ファイル: KspVersion.cs プロジェクト: zilti/CKAN
 /// <summary>
 /// Check whether a version is null or Any.
 /// We group them here because they mean the same thing.
 /// </summary>
 /// <param name="v">The version to check</param>
 /// <returns>
 /// True if null or Any, false otherwise
 /// </returns>
 public static bool IsNullOrAny(KspVersion v)
 {
     return(v == null || v.IsAny);
 }
コード例 #24
0
ファイル: KspVersionTests.cs プロジェクト: Zor-X-L/CKAN
        public void ParseWorksCorrectly(string s, KspVersion version)
        {
            // Act
            var result = KspVersion.Parse(s);

            // Assert
            Assert.AreEqual(version, result);
            Assert.AreEqual(s, result.ToString());
        }
コード例 #25
0
ファイル: KspVersionTests.cs プロジェクト: Zor-X-L/CKAN
        public void CompareToThrowsOnNullParameters()
        {
            // Act
            // ReSharper disable ReturnValueOfPureMethodIsNotUsed
            // ReSharper disable UnusedVariable
            TestDelegate actGenericCompareTo = () => new KspVersion().CompareTo(null);
            TestDelegate actNonGenericCompareTo = () => new KspVersion().CompareTo((object)null);
            TestDelegate lessThanOperatorNullLeft = () => { var _ = null < new KspVersion(); };
            TestDelegate lessThanOperatorNullRight = () => { var _ = new KspVersion() < null; };
            TestDelegate lessThanOrEqualOperatorNullLeft = () => { var _ = null <= new KspVersion(); };
            TestDelegate lessThanOrEqualOperatorNullRight = () => { var _ = new KspVersion() <= null; };
            TestDelegate greaterThanOperatorNullLeft = () => { var _ = null > new KspVersion(); };
            TestDelegate greaterThanOperatorNullRight = () => { var _ = new KspVersion() > null; };
            TestDelegate greaterThanOrEqualOperatorNullLeft = () => { var _ = null >= new KspVersion(); };
            TestDelegate greaterThanOrEqualOperatorNullRight = () => { var _ = new KspVersion() >= null; };
            // ReSharper restore UnusedVariable
            // ReSharper restore ReturnValueOfPureMethodIsNotUsed

            // Assert
            Assert.That(actGenericCompareTo, Throws.Exception);
            Assert.That(actNonGenericCompareTo, Throws.Exception);
            Assert.That(lessThanOperatorNullLeft, Throws.Exception);
            Assert.That(lessThanOperatorNullRight, Throws.Exception);
            Assert.That(lessThanOrEqualOperatorNullLeft, Throws.Exception);
            Assert.That(lessThanOrEqualOperatorNullRight, Throws.Exception);
            Assert.That(greaterThanOperatorNullLeft, Throws.Exception);
            Assert.That(greaterThanOperatorNullRight, Throws.Exception);
            Assert.That(greaterThanOrEqualOperatorNullLeft, Throws.Exception);
            Assert.That(greaterThanOrEqualOperatorNullRight, Throws.Exception);
        }
コード例 #26
0
ファイル: GUIMod.cs プロジェクト: Zor-X-L/CKAN
        public GUIMod(CkanModule mod, IRegistryQuerier registry, KspVersion current_ksp_version)
        {
            IsCKAN = mod is CkanModule;
            //Currently anything which could alter these causes a full reload of the modlist
            // If this is ever changed these could be moved into the properties
            Mod = mod;
            IsInstalled = registry.IsInstalled(mod.identifier, false);
            IsInstallChecked = IsInstalled;
            HasUpdate = registry.HasUpdate(mod.identifier, current_ksp_version);
            IsIncompatible = !mod.IsCompatibleKSP(current_ksp_version);
            IsAutodetected = registry.IsAutodetected(mod.identifier);
            Authors = mod.author == null ? "N/A" : String.Join(",", mod.author);

            var installed_version = registry.InstalledVersion(mod.identifier);
            Version latest_version = null;
            var ksp_version = mod.ksp_version;

            try
            {
                var latest_available = registry.LatestAvailable(mod.identifier, current_ksp_version);
                if (latest_available != null)
                    latest_version = latest_available.version;
            }
            catch (ModuleNotFoundKraken)
            {
                latest_version = installed_version;
            }

            InstalledVersion = installed_version != null ? installed_version.ToString() : "-";

            // Let's try to find the compatibility for this mod. If it's not in the registry at
            // all (because it's a DarkKAN mod) then this might fail.

            CkanModule latest_available_for_any_ksp = null;

            try
            {
                latest_available_for_any_ksp = registry.LatestAvailable(mod.identifier, null);
            }
            catch
            {
                // If we can't find the mod in the CKAN, but we've a CkanModule installed, then
                // use that.
                if (IsCKAN)
                    latest_available_for_any_ksp = (CkanModule) mod;

            }

            // If there's known information for this mod in any form, calculate the highest compatible
            // KSP.
            if (latest_available_for_any_ksp != null)
            {
                KSPCompatibility = KSPCompatibilityLong = latest_available_for_any_ksp.HighestCompatibleKSP();

                // If the mod we have installed is *not* the mod we have installed, or we don't know
                // what we have installed, indicate that an upgrade would be needed.
                if (installed_version == null || !latest_available_for_any_ksp.version.IsEqualTo(installed_version))
                {
                    KSPCompatibilityLong = string.Format("{0} (using mod version {1})",
                        KSPCompatibility, latest_available_for_any_ksp.version);
                }
            }
            else
            {
                // No idea what this mod is, sorry!
                KSPCompatibility = KSPCompatibilityLong = "unknown";
            }

            if (latest_version != null)
            {
                LatestVersion = latest_version.ToString();
            }
            else if (latest_available_for_any_ksp != null)
            {
                LatestVersion = latest_available_for_any_ksp.version.ToString();
            }
            else
            {
                LatestVersion = "-";
            }

            KSPversion = ksp_version != null ? ksp_version.ToString() : "-";

            Abstract = mod.@abstract;

            // If we have homepage provided use that, otherwise use the spacedock page or the github repo so that users have somewhere to get more info than just the abstract.

            Homepage = "N/A";
            if (mod.resources != null)
            {
                if (mod.resources.homepage != null)
                {
                    Homepage = mod.resources.homepage.ToString();
                }
                else if (mod.resources.spacedock != null)
                {
                    Homepage = mod.resources.spacedock.ToString();
                }
                else if (mod.resources.repository != null)
                {
                    Homepage = mod.resources.repository.ToString();
                }
            }

            Identifier = mod.identifier;

            if (mod.download_size == 0)
                DownloadSize = "N/A";
            else if (mod.download_size / 1024.0 < 1)
                DownloadSize = "1<KB";
            else
                DownloadSize = mod.download_size / 1024+"";

            Abbrevation = new string(mod.name.Split(' ').
                Where(s => s.Length > 0).Select(s => s[0]).ToArray());

            if (Main.Instance != null)
                IsCached = Main.Instance.CurrentInstance.Cache.IsMaybeCachedZip(mod.download);
        }
コード例 #27
0
ファイル: KspVersion.cs プロジェクト: zakipatel/CKAN
        /// <summary>
        /// Tries to convert the string representation of a version number to an equivalent <see cref="KspVersion"/>
        /// object and returns a value that indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="input">
        /// A string that contains a version number to convert.
        /// </param>
        /// <param name="result">
        /// When this method returns <c>true</c>, contains the <see cref="KspVersion"/> equivalent of the number that
        /// is contained in <see cref="input"/>. When this method returns <c>false</c>, the value is unspecified.
        /// </param>
        /// <returns>
        /// <c>true</c> if the <see cref="input"/> parameter was converted successfully; otherwise, <c>false</c>.
        /// </returns>
        public static bool TryParse(string input, out KspVersion result)
        {
            result = null;

            if (ReferenceEquals(input, null))
            {
                return(false);
            }

            var major = Undefined;
            var minor = Undefined;
            var patch = Undefined;
            var build = Undefined;

            var match = Pattern.Match(input.Trim());

            if (match.Success)
            {
                var majorGroup = match.Groups["major"];
                var minorGroup = match.Groups["minor"];
                var patchGroup = match.Groups["patch"];
                var buildGroup = match.Groups["build"];

                if (majorGroup.Success)
                {
                    if (!int.TryParse(majorGroup.Value, out major))
                    {
                        return(false);
                    }
                }

                if (minorGroup.Success)
                {
                    if (!int.TryParse(minorGroup.Value, out minor))
                    {
                        return(false);
                    }
                }

                if (patchGroup.Success)
                {
                    if (!int.TryParse(patchGroup.Value, out patch))
                    {
                        return(false);
                    }
                }

                if (buildGroup.Success)
                {
                    if (!int.TryParse(buildGroup.Value, out build))
                    {
                        return(false);
                    }
                }

                if (minor == Undefined)
                {
                    result = new KspVersion(major);
                }
                else if (patch == Undefined)
                {
                    result = new KspVersion(major, minor);
                }
                else if (build == Undefined)
                {
                    result = new KspVersion(major, minor, patch);
                }
                else
                {
                    result = new KspVersion(major, minor, patch, build);
                }

                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #28
0
ファイル: Registry.cs プロジェクト: CliftonMarien/CKAN
        /// <summary>
        /// <see cref="IRegistryQuerier.Incompatible"/>
        /// </summary>
        public List<CkanModule> Incompatible(KspVersion ksp_version)
        {
            var candidates = new List<string>(available_modules.Keys);
            var incompatible = new List<CkanModule>();

            // It's nice to see things in alphabetical order, so sort our keys first.
            candidates.Sort();

            // Now find what we can give our user.
            foreach (string candidate in candidates)
            {
                CkanModule available = LatestAvailable(candidate, ksp_version);

                if (available == null)
                {
                    incompatible.Add(LatestAvailable(candidate, null));
                }
            }

            return incompatible;
        }
コード例 #29
0
 private static string SameVersionString(KspVersion v)
 {
     return(v.IsAny ? "all versions" : v.ToString());
 }
コード例 #30
0
ファイル: KspVersionTests.cs プロジェクト: Zor-X-L/CKAN
        public void ToVersionRangeWorksCorrectly(KspVersion version, KspVersionRange expectedRange)
        {
            // Act
            var result = version.ToVersionRange();

            // Assert
            Assert.AreEqual(expectedRange, result);
        }
コード例 #31
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)
        {
            // Do some basic checks.
            if (textBoxNewName.TextLength == 0)
            {
                user.RaiseError("Please enter a name for the new instance.");
                return;
            }
            if (textBoxNewPath.TextLength == 0)
            {
                user.RaiseError("Please enter a path for the new instance.");
                return;
            }

            string newName = textBoxNewName.Text;
            string newPath = textBoxNewPath.Text;

            // 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("Cloning instance...");

                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 (NotKSPDirKraken kraken)
                {
                    user.RaiseError("The instance you wanted to clone is not valid: " + kraken.path);
                    reactivateDialog();
                    return;
                }
                catch (PathErrorKraken kraken)
                {
                    user.RaiseError("The destination folder is not empty: " + kraken.path);
                    reactivateDialog();
                    return;
                }
                catch (IOException ex)
                {
                    user.RaiseError($"Clone failed: {ex.Message}");
                    reactivateDialog();
                    return;
                }
                catch (Exception ex)
                {
                    user.RaiseError($"Clone failed: {ex.Message}");
                    reactivateDialog();
                    return;
                }

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

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

                user.RaiseMessage("Successfully cloned instance.");

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

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

                user.RaiseMessage("Creating new instance...");

                try
                {
                    await Task.Run(() =>
                    {
                        manager.FakeInstance(newName, newPath, kspVersion, dlcVersion);
                    });
                }
                catch (BadInstallLocationKraken)
                {
                    user.RaiseError("The destination folder is not empty or invalid.");
                    reactivateDialog();
                    return;
                }
                catch (ArgumentException)
                {
                    user.RaiseError("This name is already used.");
                    reactivateDialog();
                    return;
                }
                catch (Exception ex)
                {
                    user.RaiseError($"Fake instance creation failed: {ex.Message}");
                    reactivateDialog();
                    return;
                }

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

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

                user.RaiseMessage("Successfully created instance.");

                DialogResult = DialogResult.OK;
                this.Close();
            }
        }
コード例 #32
0
ファイル: KspVersionTests.cs プロジェクト: Zor-X-L/CKAN
        public void TryParseWorksCorrectly(string s, KspVersion version)
        {
            // Act
            KspVersion result;
            var success = KspVersion.TryParse(s, out result);

            // Assert
            Assert.IsTrue(success);
            Assert.AreEqual(version, result);
            Assert.AreEqual(s, result.ToString());
        }
コード例 #33
0
ファイル: KspVersionTests.cs プロジェクト: Zor-X-L/CKAN
        public void EqualityWorksCorrectly(KspVersion a, KspVersion b, bool areEqual)
        {
            // Act
            var genericEquality = a.Equals(b);
            var nonGenericEquality = a.Equals((object)b);
            var operatorEquality = a == b;
            var operatorInequality = a != b;
            var genericReferenceEquality = a.Equals(a);
            var nonGenericRefereneEquality = a.Equals((object)a);

            // Assert
            Assert.AreEqual(areEqual, genericEquality);
            Assert.AreEqual(areEqual, nonGenericEquality);
            Assert.AreEqual(areEqual, operatorEquality);
            Assert.AreNotEqual(areEqual, operatorInequality);
            Assert.IsTrue(genericReferenceEquality);
            Assert.IsTrue(nonGenericRefereneEquality);
        }
コード例 #34
0
ファイル: IRegistryQuerier.cs プロジェクト: Zor-X-L/CKAN
 /// <summary>
 /// Is the mod installed and does it have a newer version compatible with version
 /// We can't update AD mods
 /// </summary>
 public static bool HasUpdate(this IRegistryQuerier querier, string identifier, KspVersion version)
 {
     CkanModule newest_version;
     try
     {
         newest_version = querier.LatestAvailable(identifier, version);
     }
     catch (ModuleNotFoundKraken)
     {
         return false;
     }
     if (newest_version == null) return false;
     return !new List<string>(querier.InstalledDlls).Contains(identifier) && querier.IsInstalled(identifier, false)
         && newest_version.version.IsGreaterThan(querier.InstalledVersion(identifier));
 }
コード例 #35
0
ファイル: RelationshipResolver.cs プロジェクト: Zor-X-L/CKAN
 /// <summary>
 /// Creates a new resolver that will find a way to install all the modules specified.
 /// </summary>
 public RelationshipResolver(IEnumerable<CkanModule> modules, RelationshipResolverOptions options, IRegistryQuerier registry,
     KspVersion kspversion)
     : this(options,registry,kspversion)
 {
     AddModulesToInstall(modules);
 }
コード例 #36
0
ファイル: Registry.cs プロジェクト: CliftonMarien/CKAN
 /// <summary>
 /// <see cref = "IRegistryQuerier.LatestAvailableWithProvides" />
 /// </summary>
 public List<CkanModule> LatestAvailableWithProvides(string module, KspVersion ksp_version, RelationshipDescriptor relationship_descriptor = null)
 {
     // This public interface calculates a cache of modules which
     // are compatible with the current version of KSP, and then
     // calls the private version below for heavy lifting.
     return LatestAvailableWithProvides(module, ksp_version,
         available_modules.Values.Select(pair => pair.Latest(ksp_version)).Where(mod => mod != null).ToArray(),
         relationship_descriptor);
 }
コード例 #37
0
ファイル: KSP.cs プロジェクト: Zor-X-L/CKAN
        public KspVersion Version()
        {
            if (version != null)
            {
                return version;
            }

            return version = DetectVersion(GameDir());
        }
コード例 #38
0
ファイル: Registry.cs プロジェクト: CliftonMarien/CKAN
        /// <summary>
        /// Returns the latest version of a module that can be installed for
        /// the given KSP version. This is a *private* method that assumes
        /// the `available_for_current_version` list has been correctly
        /// calculated. Not for direct public consumption. ;)
        /// </summary>
        private List<CkanModule> LatestAvailableWithProvides(string module, KspVersion ksp_version,
            IEnumerable<CkanModule> available_for_current_version, RelationshipDescriptor relationship_descriptor=null)
        {
            log.DebugFormat("Finding latest available with provides for {0}", module);

            // TODO: Check user's stability tolerance (stable, unstable, testing, etc)

            var modules = new List<CkanModule>();

            try
            {
                // If we can find the module requested for our KSP, use that.
                CkanModule mod = LatestAvailable(module, ksp_version, relationship_descriptor);
                if (mod != null)
                {
                    modules.Add(mod);
                }
            }
            catch (ModuleNotFoundKraken)
            {
                // It's cool if we can't find it, though.
            }

            // Walk through all our available modules, and see if anything
            // provides what we need.

            // Get our candidate module. We can assume this is non-null, as
            // if it *is* null then available_for_current_version is corrupted,
            // and something is terribly wrong.
            foreach (CkanModule candidate in available_for_current_version)
            {
                // Find everything this module provides (for our version of KSP)
                List<string> provides = candidate.provides;

                // If the module has provides, and any of them are what we're looking
                // for, the add it to our list.
                if (provides != null && provides.Any(provided => provided == module))
                {
                    modules.Add(candidate);
                }
            }
            return modules;
        }
コード例 #39
0
ファイル: KspVersion.cs プロジェクト: KSP-CKAN/CKAN
        /// <summary>
        /// Tries to convert the string representation of a version number to an equivalent <see cref="KspVersion"/>
        /// object and returns a value that indicates whether the conversion succeeded.
        /// </summary>
        /// <param name="input">
        /// A string that contains a version number to convert.
        /// </param>
        /// <param name="result">
        /// When this method returns <c>true</c>, contains the <see cref="KspVersion"/> equivalent of the number that
        /// is contained in <see cref="input"/>. When this method returns <c>false</c>, the value is unspecified.
        /// </param>
        /// <returns>
        /// <c>true</c> if the <see cref="input"/> parameter was converted successfully; otherwise, <c>false</c>.
        /// </returns>
        public static bool TryParse(string input, out KspVersion result)
        {
            result = null;

            if (ReferenceEquals(input, null))
                return false;

            var major = Undefined;
            var minor = Undefined;
            var patch = Undefined;
            var build = Undefined;

            var match = Pattern.Match(input.Trim());

            if (match.Success)
            {
                var majorGroup = match.Groups["major"];
                var minorGroup = match.Groups["minor"];
                var patchGroup = match.Groups["patch"];
                var buildGroup = match.Groups["build"];

                if (majorGroup.Success)
                    if (!int.TryParse(majorGroup.Value, out major))
                        return false;

                if (minorGroup.Success)
                    if (!int.TryParse(minorGroup.Value, out minor))
                        return false;

                if (patchGroup.Success)
                    if (!int.TryParse(patchGroup.Value, out patch))
                        return false;

                if (buildGroup.Success)
                    if (!int.TryParse(buildGroup.Value, out build))
                        return false;

                if (minor == Undefined)
                    result = new KspVersion(major);
                else if (patch == Undefined)
                    result = new KspVersion(major, minor);
                else if (build == Undefined)
                    result = new KspVersion(major, minor, patch);
                else
                    result = new KspVersion(major, minor, patch, build);

                return true;
            }
            else
            {
                return false;
            }
        }
コード例 #40
0
ファイル: KspVersionTests.cs プロジェクト: Zor-X-L/CKAN
        public void CompareToWorksCorrectly(KspVersion v1, KspVersion v2, int comparison)
        {
            // Act
            var genericCompareTo = v1.CompareTo(v2);
            var nonGenericCompareTo = v1.CompareTo((object)v2);
            var lessThanOperator = v1 < v2;
            var lessThanOrEqualOperator = v1 <= v2;
            var greaterThanOperator = v1 > v2;
            var greaterThanOrEqualOperator = v1 >= v2;

            var reverseGenericCompareTo = v2.CompareTo(v1);
            var reverseNonGenericCompareTo = v2.CompareTo((object)v1);
            var reverseLessThanOperator = v2 < v1;
            var reverseLessThanOrEqualOperator = v2 <= v1;
            var reverseGreaterThanOperator = v2 > v1;
            var reverseGreaterThanOrEqualOperator = v2 >= v1;

            // Assert
            Assert.AreEqual(Math.Sign(comparison), Math.Sign(genericCompareTo));
            Assert.AreEqual(Math.Sign(comparison), Math.Sign(nonGenericCompareTo));
            Assert.AreEqual(comparison < 0, lessThanOperator);
            Assert.AreEqual(comparison <= 0, lessThanOrEqualOperator);
            Assert.AreEqual(comparison > 0, greaterThanOperator);
            Assert.AreEqual(comparison >= 0, greaterThanOrEqualOperator);
            Assert.AreEqual(-Math.Sign(comparison), Math.Sign(reverseGenericCompareTo));
            Assert.AreEqual(-Math.Sign(comparison), Math.Sign(reverseNonGenericCompareTo));
            Assert.AreEqual(comparison > 0, reverseLessThanOperator);
            Assert.AreEqual(comparison >= 0, reverseLessThanOrEqualOperator);
            Assert.AreEqual(comparison < 0, reverseGreaterThanOperator);
            Assert.AreEqual(comparison <= 0, reverseGreaterThanOrEqualOperator);
        }
コード例 #41
0
ファイル: CloneFakeKspDialog.cs プロジェクト: MrGarak/CKAN
        /// <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)
        {
            // Do some basic checks.
            if (textBoxNewName.TextLength == 0)
            {
                user.RaiseError(Properties.Resources.CloneFakeKspDialogEnterName);
                return;
            }
            if (textBoxNewPath.TextLength == 0)
            {
                user.RaiseError(Properties.Resources.CloneFakeKspDialogEnterPath);
                return;
            }

            string newName = textBoxNewName.Text;
            string newPath = textBoxNewPath.Text;

            // 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 (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)
            {
                Versioning.KspVersion kspVersion = Versioning.KspVersion.Parse(comboBoxKspVersion.Text);
                string dlcVersion = textBoxDlcVersion.Text;

                user.RaiseMessage(Properties.Resources.CloneFakeKspDialogCreatingInstance);

                try
                {
                    await Task.Run(() =>
                    {
                        manager.FakeInstance(newName, newPath, kspVersion, dlcVersion);
                    });
                }
                catch (BadInstallLocationKraken)
                {
                    user.RaiseError(Properties.Resources.CloneFakeKspDialogDestinationNotEmpty);
                    reactivateDialog();
                    return;
                }
                catch (ArgumentException)
                {
                    user.RaiseError(Properties.Resources.CloneFakeKspDialogNameAlreadyUsed);
                    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();
            }
        }
コード例 #42
0
ファイル: Registry.cs プロジェクト: CliftonMarien/CKAN
        /// <summary>
        /// <see cref="IRegistryQuerier.Available"/>
        /// </summary>
        public List<CkanModule> Available(KspVersion ksp_version)
        {
            var candidates = new List<string>(available_modules.Keys);
            var compatible = new List<CkanModule>();

            // It's nice to see things in alphabetical order, so sort our keys first.
            candidates.Sort();

            //Cache
            CkanModule[] modules_for_current_version = available_modules.Values.Select(pair => pair.Latest(ksp_version)).Where(mod => mod != null).ToArray();
            // Now find what we can give our user.
            foreach (string candidate in candidates)
            {
                CkanModule available = LatestAvailable(candidate, ksp_version);

                if (available != null)
                {
                    // we need to check that we can get everything we depend on
                    bool failedDepedency = false;

                    if (available.depends != null)
                    {
                        foreach (RelationshipDescriptor dependency in available.depends)
                        {
                            try
                            {
                                if (!LatestAvailableWithProvides(dependency.name, ksp_version, modules_for_current_version).Any())
                                {
                                    failedDepedency = true;
                                    break;
                                }
                            }
                            catch (KeyNotFoundException e)
                            {
                                log.ErrorFormat("Cannot find available version with provides for {0} in registry", dependency.name);
                                throw e;
                            }
                            catch (ModuleNotFoundKraken)
                            {
                                failedDepedency = true;
                                break;
                            }
                        }
                    }

                    if (!failedDepedency)
                    {
                        compatible.Add(available);
                    }
                }
            }

            return compatible;
        }
コード例 #43
0
ファイル: Kraken.cs プロジェクト: yixi435/CKAN
 public WrongKSPVersionKraken(Versioning.KspVersion version, string reason = null, Exception inner_exception = null)
     : base(reason, inner_exception)
 {
     this.version = version;
 }
コード例 #44
0
ファイル: KspVersionRange.cs プロジェクト: waralper1/CKAN
 public KspVersionRange(KspVersion lower, KspVersion upper)
     : this(lower?.ToVersionRange().Lower, upper?.ToVersionRange().Upper)
 {
 }