Пример #1
0
        public async Task UpdateArtifactDependency(string buildConfigId, DependencyDefinition artifactDependency)
        {
            Log.TraceFormat("API BuildConfig.UpdateArtifactDependency for: {0}, artifactDependency: {{{1}}}", buildConfigId, artifactDependency);

            var url = string.Format("/app/rest/buildTypes/id:{0}/artifact-dependencies/{1}", buildConfigId, artifactDependency.Id);
            await _http.PutJson(url, Json.Serialize(artifactDependency));
        }
Пример #2
0
        public CompareResult CompareVersions(Upset package, DependencyDefinition dependencyDefinition)
        {
            VersionStruct packageVersion    = ParseVersion(package);
            VersionStruct dependencyVersion = ParseVersion(dependencyDefinition);

            return(CompareVersions(packageVersion, dependencyVersion));
        }
Пример #3
0
            public void Snapshot()
            {
                var client    = CreateBuildConfigClient();
                var summaries = client.GetAll().Result;
                //var buildConfig = client.GetByConfigurationId("FooCore_Master").Result;
                var buildConfig          = summaries.First(x => x.Id == "FooCore_Master");
                var dependencyDefinition = new DependencyDefinition
                {
                    Id         = buildConfig.Id,
                    Type       = "snapshot_dependency",
                    Properties = new Properties
                    {
                        Property = new PropertyList
                        {
                            new Property()
                            {
                                Name = "run-build-if-dependency-failed", Value = BuildContinuationMode.MakeFailedToStart.ToString()
                            },
                            new Property()
                            {
                                Name = "take-successful-builds-only", Value = "true"
                            },
                            //new Property() { Name = "run-build-on-the-same-agent", Value = "true" },
                            //new Property() { Name = "take-started-build-with-same-revisions", Value = "true" },
                        }
                    },
                    SourceBuildConfig = buildConfig
                };

                client.CreateDependency("foo_service_Master", dependencyDefinition).Wait();
            }
Пример #4
0
        private void DependencyStateBlock(
            DependencyDefinition definition,
            PackageRepo bestMatch,
            PackageRepo latest,
            InstalledPackage installed
            )
        {
            EditorGUILayout.LabelField(definition.Name + ":", EditorStyles.boldLabel);
            EditorGUILayout.LabelField("Requirement: " + definition.Requirement.ToString());
            if (installed != null)
            {
                EditorGUILayout.LabelField("Installed version: " + installed.Version);

                if (VersionParser.GreaterThan(bestMatch.Package.PackageVersion, installed.Version))
                {
                    EditorGUILayout.HelpBox(
                        string.Format(
                            "Package is outdated. You can update it to {0} (from {1})",
                            bestMatch.Package.PackageVersion,
                            bestMatch.Repository.ToString()
                            ),
                        MessageType.Info
                        );
                    if (GUILayout.Button("Update to version " + bestMatch.Package.PackageVersion))
                    {
                        UpliftManager.Instance().UpdatePackage(bestMatch, updateLockfile: true);
                        Init();
                        Repaint();
                    }
                }
                else
                {
                    EditorGUILayout.HelpBox("Package is up to date!", MessageType.Info);
                }

                if (!definition.Requirement.IsMetBy(installed.Version))
                {
                    EditorGUILayout.HelpBox(
                        "The version of the package currently installed does not match the requirements of your project!",
                        installed.Version != bestMatch.Package.PackageVersion ? MessageType.Warning : MessageType.Error
                        );
                }
            }
            else
            {
                EditorGUILayout.LabelField("Not yet installed");
            }

            if (latest.Package.PackageVersion != bestMatch.Package.PackageVersion)
            {
                EditorGUILayout.HelpBox(
                    string.Format(
                        "Note: there is a more recent version of the package ({0} from {1}), but it doesn't match your requirement",
                        latest.Package.PackageVersion,
                        bestMatch.Repository.ToString()
                        ),
                    MessageType.Info
                    );
            }
        }
Пример #5
0
        private void UpdatePackage(Upset package, TemporaryDirectory td)
        {
            NukePackage(package.PackageName);

            DependencyDefinition definition = Upfile.Instance().Dependencies.First(dep => dep.Name == package.PackageName);

            InstallPackage(package, td, definition, true);
        }
Пример #6
0
        public void InstallPackages(PackageRepo[] targets, bool updateLockfile = true)
        {
            Debug.Log("Install Packages");
            using (LogAggregator LA = LogAggregator.InUnity(
                       "Successfully installed dependencies ({0} actions were done)",
                       "Successfully installed dependencies ({0} actions were done) but warnings were raised",
                       "Some errors occured while installing dependencies",
                       targets.Length
                       ))
            {
                // Remove installed dependencies that are no longer in the dependency tree

                foreach (InstalledPackage ip in Upbring.Instance().InstalledPackage)
                {
                    if (targets.Any(tar => tar.Package.PackageName == ip.Name))
                    {
                        continue;
                    }

                    UnityEngine.Debug.Log("Removing unused dependency on " + ip.Name);

                    NukePackage(ip.Name);
                }

                foreach (PackageRepo pr in targets)
                {
                    if (pr.Repository != null)
                    {
                        if (Upbring.Instance().InstalledPackage.Any(ip => ip.Name == pr.Package.PackageName))
                        {
                            Debug.Log("update " + pr.Package.PackageName);
                            UpdatePackage(pr, updateDependencies: false, updateLockfile: updateLockfile);
                        }
                        else
                        {
                            DependencyDefinition def = upfile.Dependencies.Any(d => d.Name == pr.Package.PackageName) ?
                                                       upfile.Dependencies.First(d => d.Name == pr.Package.PackageName) :
                                                       new DependencyDefinition()
                            {
                                Name = pr.Package.PackageName, Version = pr.Package.PackageVersion
                            };

                            using (TemporaryDirectory td = pr.Repository.DownloadPackage(pr.Package))
                            {
                                Debug.Log("install " + pr.Package.PackageName);
                                InstallPackage(pr.Package, td, def, updateLockfile);
                            }
                        }
                    }
                    else
                    {
                        UnityEngine.Debug.LogError("No repository for package " + pr.Package.PackageName);
                    }
                }
            }
            UnityHacks.BuildSettingsEnforcer.EnforceAssetSave();
        }
Пример #7
0
        public async Task CreateDependency(string targetBuildConfigId, DependencyDefinition dependencyDefinition)
        {
            var xml = CreateDependencyXml(dependencyDefinition);

            Log.TraceFormat("API BuildConfig.CreateDependency for: {0}, dependency: {1}", targetBuildConfigId, xml);

            var url = string.Format("/app/rest/buildTypes/{0}/{1}-dependencies", targetBuildConfigId, dependencyDefinition.Type.Split('_')[0]);

            await _http.PostXml(url, xml);
        }
Пример #8
0
 public DependencyNode(DependencyDefinition definition) : this(
         definition.Name,
         definition.Version,
         definition.Repository,
         definition.SkipInstall,
         definition.OverrideDestination,
         null
         )
 {
 }
Пример #9
0
        private DependencyDefinition DependencyField(DependencyDefinition def)
        {
            DependencyDefinition temp = def;

            EditorGUILayout.BeginVertical();
            EditorGUILayout.BeginHorizontal();
            temp.Name    = EditorGUILayout.TextField("Package Name:", temp.Name);
            temp.Version = EditorGUILayout.TextField("Package Version:", temp.Version);
            EditorGUILayout.EndHorizontal();
            OverrideDestinationSpec defaultODS = new OverrideDestinationSpec {
                Type = InstallSpecType.Base, Location = "Enter a location"
            };
            SkipInstallSpec defaultSIS = new SkipInstallSpec {
                Type = InstallSpecType.Docs
            };

            if (temp.OverrideDestination != null)
            {
                temp.OverrideDestination = ArrayField <OverrideDestinationSpec>(
                    temp.OverrideDestination,
                    "Do not override this",
                    "Override another type",
                    defaultODS,
                    ods => OverrideDestinationField(ods)
                    );
            }
            else
            {
                if (GUILayout.Button("Declare some installation overrides"))
                {
                    temp.OverrideDestination = new OverrideDestinationSpec[] { defaultODS };
                }
            }
            if (temp.SkipInstall != null)
            {
                temp.SkipInstall = ArrayField <SkipInstallSpec>(
                    temp.SkipInstall,
                    "Do not skip this",
                    "Skip another type",
                    defaultSIS,
                    sis => SkipInstallField(sis)
                    );
            }
            else
            {
                if (GUILayout.Button("Declare some installation skips"))
                {
                    temp.SkipInstall = new SkipInstallSpec[] { defaultSIS };
                }
            }
            EditorGUILayout.Separator();
            EditorGUILayout.EndVertical();

            return(temp);
        }
 private bool ContainsItem(List <ProfilingTypeFacade> sortedItems, DependencyDefinition dependency)
 {
     foreach (ProfilingTypeFacade item in sortedItems)
     {
         if (item.Definition.Uid == dependency.Uid)
         {
             return(true);
         }
     }
     return(false);
 }
Пример #11
0
        public void UpdatePackage(Upset package, TemporaryDirectory td)
        {
            Upbring upbring = Upbring.Instance();

            // Nuking previous version
            InstalledPackage installedPackage = upbring.GetInstalledPackage(package.PackageName);

            installedPackage.Nuke();

            DependencyDefinition definition = Upfile.Instance().Dependencies.First(dep => dep.Name == package.PackageName);

            InstallPackage(package, td, definition);
        }
Пример #12
0
 internal PackageRepo[] FindCandidatesForDefinition(DependencyDefinition packageDefinition)
 {
     return((
                // From All the available packages
                from packageRepo in GetAllPackages()
                // Select the ones that match the definition name
                where packageRepo.Package.PackageName == packageDefinition.Name
                // And the version definition
                where versionParser.GreaterThan(packageRepo.Package, packageDefinition)
                // And use found package
                select packageRepo
                // As an array
                ).ToArray());
 }
Пример #13
0
        private string RecursivelyListDependencies(DependencyDefinition def, string indent = "")
        {
            string      result = indent + def.Name + " " + def.Requirement + " " + def.Version + "\n";
            PackageRepo pr     = PackageList.Instance().FindPackageAndRepository(def);

            if (pr.Package != null && pr.Package.Dependencies != null)
            {
                foreach (DependencyDefinition packageDefinition in pr.Package.Dependencies)
                {
                    result += RecursivelyListDependencies(packageDefinition, indent + "   ");
                }
            }
            return(result);
        }
Пример #14
0
        private static List <ArtifactRule> GetArtifactRules(DependencyDefinition dependency)
        {
            Property artifactRulesProperty =
                dependency.Properties.Property.FirstOrDefault(
                    x => x.Name.Equals("pathRules", StringComparison.InvariantCultureIgnoreCase));

            if (artifactRulesProperty == null || string.IsNullOrWhiteSpace(artifactRulesProperty.Value))
            {
                throw new Exception(string.Format("Missing or invalid Artifact dependency. ProjectId: {0}", dependency.SourceBuildConfig.ProjectId));
            }

            List <ArtifactRule> artifactRules = ArtifactRule.Parse(artifactRulesProperty.Value);

            return(artifactRules);
        }
Пример #15
0
        private async Task ResolveDependency(DependencyDefinition dependency, EscrowElement escrowElement)
        {
            Log.Debug("Trying to fetch dependency: {0}", dependency.SourceBuildConfig.Id);

            if (_builds.ContainsKey(dependency.SourceBuildConfig.Id))
            {
                Log.Info("Dependency already fetched. Skipping: {0}", dependency.SourceBuildConfig.Id);
                return;
            }

            EscrowArtifactDependency escrowArtifact =
                escrowElement.ArtifactDependencies.FirstOrDefault(x => x.BuildTypeId == dependency.SourceBuildConfig.Id);

            if (escrowArtifact == null)
            {
                Log.Info("Cannot find dependency defined in escrow docucment: {0}", dependency.SourceBuildConfig.Id);
                return;
            }

            Build build = await _client.Builds.ById(escrowArtifact.Id);

            lock (_builds)
            {
                _builds.Add(build.BuildTypeId, BuildInfo.FromBuild(build));
            }

            Log.Debug("Downloading artifacts from: {0}-{1}", build.BuildTypeId, build.Number);

            List <ArtifactRule> artifactRules = GetArtifactRules(dependency);

            string basePath = _fileSystem.GetWorkingDirectory();

            if (string.IsNullOrWhiteSpace(basePath))
            {
                basePath = ".";
            }

            List <PathFilePair> files = new List <PathFilePair>();

            foreach (ArtifactRule artifactRule in artifactRules)
            {
                files.AddRange(await FetchFileListForArtifactRule(artifactRule, build, basePath));
            }

            DownloadFiles(files);

            Log.Debug("Done fetching dependency for: {0}", dependency.SourceBuildConfig.Id);
        }
Пример #16
0
        private static string CreateDependencyXml(DependencyDefinition definition)
        {
            var element = new XElement(definition.Type.Replace('_', '-'),
                                       new XAttribute("id", definition.Id),
                                       new XAttribute("type", definition.Type),
                                       new XElement("properties", definition.Properties.Property.Select(x => new XElement("property", new XAttribute("name", x.Name), new XAttribute("value", x.Value))).ToArray()),
                                       new XElement("source-buildType", new XAttribute("id", definition.SourceBuildConfig.Id),
                                                    new XAttribute("name", definition.SourceBuildConfig.Name),
                                                    new XAttribute("href", definition.SourceBuildConfig.Href),
                                                    new XAttribute("projectName", definition.SourceBuildConfig.ProjectName),
                                                    new XAttribute("projectId", definition.SourceBuildConfig.ProjectId),
                                                    new XAttribute("webUrl", definition.SourceBuildConfig.WebUrl))
                                       );

            return(element.ToString());
        }
Пример #17
0
        private void UpdatePackage(Upset package, TemporaryDirectory td, bool updateLockfile)
        {
            NukePackage(package.PackageName);

            // First or default returns the first DependencyDefinition which satistfies dep.Name == package.PackageName
            // If no elements meets this condition a Default value for DependencyDefinition is returned which, for our implementation, is null.
            DependencyDefinition definition = Upfile.Instance().Dependencies.FirstOrDefault(dep => dep.Name == package.PackageName);

            if (definition == null)
            {
                definition = new DependencyDefinition()
                {
                    Name = package.PackageName, Version = package.PackageVersion
                };
            }

            InstallPackage(package, td, definition, updateLockfile);
        }
        private DependencyDefinition[] GetDependencyDefinitions(DependencyGraph graph)
        {
            DependencyDefinition[] result = new DependencyDefinition[graph.nodeList.Count];
            DependencyNode         current;

            for (int i = 0; i < graph.nodeList.Count; i++)
            {
                current   = graph.nodeList[i];
                result[i] = new DependencyDefinition()
                {
                    Name       = current.Name,
                    Version    = current.Version,
                    Repository = current.Repository
                };
            }

            return(result);
        }
Пример #19
0
        internal PackageRepo FindPackageAndRepository(DependencyDefinition packageDefinition)
        {
            PackageRepo blankResult = new PackageRepo();

            PackageRepo[] candidates = FindCandidatesForDefinition(packageDefinition);

            candidates = SelectCandidates(candidates, new LatestSelectionStrategy());

            if (candidates.Length > 0)
            {
                return(candidates[0]);
            }
            else
            {
                Debug.LogWarning("Package: " + packageDefinition.Name + " not found");
                return(blankResult);
            }
        }
Пример #20
0
        private static BuildConfig ConfigureDependency(ITeamCityClient client, DependencyDefinition dependencyDefinition, IFixture fixture)
        {
            Build build = fixture.Build <Build>()
                          .With(x => x.BuildTypeId, dependencyDefinition.SourceBuildConfig.Id)
                          .Create();

            BuildConfig buildConfig = fixture.Build <BuildConfig>()
                                      .WithId(dependencyDefinition.SourceBuildConfig.Id)
                                      .WithNoDependencies()
                                      .Create();

            client.BuildConfigs.GetByConfigurationId(dependencyDefinition.SourceBuildConfig.Id)
            .Returns(Task.FromResult(buildConfig));

            client.Builds.LastSuccessfulBuildFromConfig(dependencyDefinition.SourceBuildConfig.Id)
            .Returns(Task.FromResult(build));

            return(buildConfig);
        }
Пример #21
0
        public async Task CreateSnapshotDependency(CreateSnapshotDependency dependency)
        {
            Log.DebugFormat("API BuildConfig.CreateSnapshotDependency for: {0}, to: {0}", dependency.TargetBuildConfigId, dependency.DependencyBuildConfigId);

            string requestUri = string.Format("/app/rest/buildTypes/id:{0}", dependency.DependencyBuildConfigId);

            BuildConfigSummary buildConfig = await _http.Get <BuildConfigSummary>(requestUri);

            var dependencyDefinition = new DependencyDefinition
            {
                Id         = buildConfig.Id,
                Type       = "snapshot_dependency",
                Properties = new Properties
                {
                    Property = new PropertyList
                    {
                        new Property()
                        {
                            Name = "run-build-if-dependency-failed", Value = dependency.RunBuildIfDependencyFailed.ToString()
                        },
                        new Property()
                        {
                            Name = "run-build-if-dependency-failed-to-start", Value = dependency.RunBuildIfDependencyFailed.ToString()
                        },
                        new Property()
                        {
                            Name = "take-successful-builds-only", Value = dependency.TakeSuccessFulBuildsOnly.ToString()
                        },
                        new Property()
                        {
                            Name = "run-build-on-the-same-agent", Value = dependency.RunBuildOnTheSameAgent.ToString()
                        },
                        new Property()
                        {
                            Name = "take-started-build-with-same-revisions", Value = dependency.TakeStartedBuildWithSameRevisions.ToString()
                        },
                    }
                },
                SourceBuildConfig = buildConfig
            };

            await CreateDependency(dependency.TargetBuildConfigId, dependencyDefinition);
        }
Пример #22
0
        private async Task ResolveDependency(DependencyDefinition dependency, string tag)
        {
            Log.Debug("Trying to fetch dependency: {0}", dependency.SourceBuildConfig.Id);

            if (_builds.ContainsKey(dependency.SourceBuildConfig.Id))
            {
                Log.Info("Dependency already fetched. Skipping: {0}", dependency.SourceBuildConfig.Id);
                return;
            }

            Build build;

            if (dependency.Properties.Property["revisionName"].Value == "buildNumber")
            {
                build = await _client.Builds.ByNumber(dependency.Properties.Property["revisionValue"].Value, dependency.SourceBuildConfig.Id);
            }
            else
            {
                build = await _client.Builds.LastSuccessfulBuildFromConfig(dependency.SourceBuildConfig.Id, tag);
            }

            lock (_builds)
            {
                _builds.Add(build.BuildTypeId, BuildInfo.FromBuild(build));
            }

            Log.Debug("Downloading artifacts from: {0}-{1}", build.BuildTypeId, build.Number);

            List <ArtifactRule> artifactRules = GetArtifactRules(dependency);

            //create fake files with the reference to the TC resources in order to download.
            List <PathFilePair> files = artifactRules.Select(x => new PathFilePair
            {
                File = x.CreateTeamCityFileReference(build.Href + "/artifacts/content/"),
                Path = Path.Combine(".", x.Dest)
            }).ToList();

            DownloadFiles(files);

            Log.Debug("Done fetching dependency for: {0}", dependency.SourceBuildConfig.Id);
        }
Пример #23
0
        private DependencyDefinition[] GetDependencyDefinitions(DependencyGraph graph)
        {
            DependencyDefinition[] result = new DependencyDefinition[graph.nodeList.Count];
            DependencyNode         current;

            for (int i = 0; i < graph.nodeList.Count; i++)
            {
                current = graph.nodeList[i];

                result[i] = new DependencyDefinition()
                {
                    Name                = current.Name,
                    Version             = current.Requirement.ToString(),
                    Repository          = current.Repository,
                    SkipInstall         = current.skips,
                    OverrideDestination = current.overrides
                };
            }

            return(result);
        }
Пример #24
0
        public async Task CreateArtifactDependency(CreateArtifactDependency dependency)
        {
            Log.DebugFormat("API BuildConfig.CreateArtifactDependency for: {0}, to: {1}", dependency.TargetBuildConfigId, dependency.DependencyBuildConfigId);

            string requestUri = string.Format("/app/rest/buildTypes/id:{0}", dependency.DependencyBuildConfigId);

            BuildConfigSummary buildConfig = await _http.Get <BuildConfigSummary>(requestUri);

            var dependencyDefinition = new DependencyDefinition
            {
                Id         = "0",
                Type       = "artifact_dependency",
                Properties = new Properties
                {
                    Property = new PropertyList
                    {
                        new Property()
                        {
                            Name = "cleanDestinationDirectory", Value = dependency.CleanDestinationDirectory.ToString()
                        },
                        new Property()
                        {
                            Name = "pathRules", Value = dependency.PathRules
                        },
                        new Property()
                        {
                            Name = "revisionName", Value = dependency.RevisionName
                        },
                        new Property()
                        {
                            Name = "revisionValue", Value = dependency.RevisionValue
                        },
                    }
                },
                SourceBuildConfig = buildConfig
            };

            await CreateDependency(dependency.TargetBuildConfigId, dependencyDefinition);
        }
Пример #25
0
        public void LoadDependencies(DependencyDefinition dependency, PackageList packageList, DependencyHelper.ConflictChecker checkConflict, out DependencyNode node)
        {
            node = new DependencyNode(dependency);

            if (Contains(dependency.Name))
            {
                DependencyNode existing = FindByName(dependency.Name);
                checkConflict(ref existing, node);
            }
            else
            {
                nodeList.Add(node);

                Upset package = packageList.FindPackageAndRepository(dependency).Package;
                if (package == null)
                {
                    throw new MissingDependencyException(string.Format(" depends on {0} ({1}) but it is not present in any of your specified repository", dependency.Name, dependency.Requirement));
                }

                if (package.Dependencies != null)
                {
                    DependencyNode child;
                    foreach (DependencyDefinition packageDependency in package.Dependencies)
                    {
                        child = null;
                        try
                        {
                            LoadDependencies(packageDependency, packageList, checkConflict, out child);
                            AddDependency(node, child);
                        }
                        catch (MissingDependencyException e)
                        {
                            throw new MissingDependencyException(dependency.Name + e.Message);
                        }
                    }
                }
            }
        }
Пример #26
0
        private void AppendDependencyState(
            ref List <DependencyState> dependenciesState,
            DependencyDefinition definition,
            PackageRepo[] targets,
            bool anyInstalled,
            bool transitive = false
            )
        {
            Upbring upbring = Upbring.Instance();

            DependencyState state = new DependencyState
            {
                definition = definition,
                latest     = PackageList.Instance().GetLatestPackage(definition.Name)
            };

            state.bestMatch = targets.First(pr => pr.Package.PackageName == definition.Name);
            if (anyInstalled && upbring.InstalledPackage.Any(ip => ip.Name == definition.Name))
            {
                state.installed = upbring.InstalledPackage.First(ip => ip.Name == definition.Name);
            }
            state.transitive = transitive;

            dependenciesState.Add(state);
            if (state.bestMatch.Package.Dependencies != null)
            {
                foreach (DependencyDefinition dependency in state.bestMatch.Package.Dependencies)
                {
                    AppendDependencyState(
                        ref dependenciesState,
                        dependency,
                        targets,
                        anyInstalled,
                        true
                        );
                }
            }
        }
Пример #27
0
        public DependencyDefinition[] ListDependenciesRecursively(DependencyDefinition packageDefinition)
        {
            DependencyDefinition[] dependencies = new DependencyDefinition[0];

            PackageRepo pr = FindPackageAndRepository(packageDefinition);

            if (pr.Package != null && pr.Package.Dependencies != null)
            {
                dependencies = pr.Package.Dependencies;
                foreach (DependencyDefinition def in pr.Package.Dependencies)
                {
                    // Aggregate results
                    DependencyDefinition[] packageDependencies = ListDependenciesRecursively(def);
                    int newLength = packageDependencies.Length + dependencies.Length;
                    DependencyDefinition[] newDeps = new DependencyDefinition[newLength];
                    Array.Copy(dependencies, newDeps, dependencies.Length);
                    Array.Copy(packageDependencies, 0, newDeps, dependencies.Length, packageDependencies.Length);

                    dependencies = newDeps;
                }
            }
            return(dependencies);
        }
Пример #28
0
        internal PackageRepo FindPackageAndRepository(DependencyDefinition packageDefinition)
        {
            PackageRepo blankResult = new PackageRepo();

            PackageRepo[] candidates = FindCandidatesForDefinition(packageDefinition);

            var strategies = new CandidateSelectionStrategy[] {
                new OnlyMatchingUnityVersionStrategy(Application.unityVersion),
                new FindBestPackageForUnityVersion(Application.unityVersion),
                new LatestSelectionStrategy()
            };

            candidates = SelectCandidates(candidates, strategies);

            if (candidates.Length > 0)
            {
                return(candidates[0]);
            }
            else
            {
                Debug.LogWarning("No package " + packageDefinition.Name + " matching requirements was found");
                return(blankResult);
            }
        }
Пример #29
0
        //FIXME: This is super unsafe right now, as we can copy down into the FS.
        // This should be contained using kinds of destinations.
        private void InstallPackage(Upset package, TemporaryDirectory td, DependencyDefinition dependencyDefinition, bool updateLockfile = false)
        {
            GitIgnorer VCSHandler = new GitIgnorer();

            using (LogAggregator LA = LogAggregator.InUnity(
                       "Package {0} was successfully installed",
                       "Package {0} was successfully installed but raised warnings",
                       "An error occured while installing package {0}",
                       package.PackageName
                       ))
            {
                Upbring upbring = Upbring.Instance();

                // Note: Full package is ALWAYS copied to the upackages directory right now
                string localPackagePath = GetRepositoryInstallPath(package);
                upbring.AddPackage(package);
                if (!Directory.Exists(localPackagePath))
                {
                    Directory.CreateDirectory(localPackagePath);
                }

                Uplift.Common.FileSystemUtil.CopyDirectory(td.Path, localPackagePath);
                upbring.AddLocation(package, InstallSpecType.Root, localPackagePath);

                VCSHandler.HandleDirectory(upfile.GetPackagesRootPath());

                InstallSpecPath[] specArray;
                if (package.Configuration == null)
                {
                    // If there is no Configuration present we assume
                    // that the whole package is wrapped in "InstallSpecType.Base"
                    InstallSpecPath wrapSpec = new InstallSpecPath
                    {
                        Path = "",
                        Type = InstallSpecType.Base
                    };

                    specArray = new[] { wrapSpec };
                }
                else
                {
                    specArray = package.Configuration;
                }

                foreach (InstallSpecPath spec in specArray)
                {
                    if (dependencyDefinition.SkipInstall != null && dependencyDefinition.SkipInstall.Any(skip => skip.Type == spec.Type))
                    {
                        continue;
                    }

                    var sourcePath = Uplift.Common.FileSystemUtil.JoinPaths(td.Path, spec.Path);

                    PathConfiguration PH = upfile.GetDestinationFor(spec);
                    if (dependencyDefinition.OverrideDestination != null && dependencyDefinition.OverrideDestination.Any(over => over.Type == spec.Type))
                    {
                        PH.Location = Uplift.Common.FileSystemUtil.MakePathOSFriendly(dependencyDefinition.OverrideDestination.First(over => over.Type == spec.Type).Location);
                    }

                    var packageStructurePrefix =
                        PH.SkipPackageStructure ? "" : GetPackageDirectory(package);

                    var destination = Path.Combine(PH.Location, packageStructurePrefix);

                    // Working with single file
                    if (File.Exists(sourcePath))
                    {
                        // Working with singular file
                        if (!Directory.Exists(destination))
                        {
                            Directory.CreateDirectory(destination);
                            VCSHandler.HandleFile(destination);
                        }
                        if (Directory.Exists(destination))
                        { // we are copying a file into a directory
                            destination = System.IO.Path.Combine(destination, System.IO.Path.GetFileName(sourcePath));
                        }
                        File.Copy(sourcePath, destination);
                        Uplift.Common.FileSystemUtil.TryCopyMeta(sourcePath, destination);

                        if (destination.StartsWith("Assets"))
                        {
                            TryUpringAddGUID(upbring, sourcePath, package, spec.Type, destination);
                        }
                        else
                        {
                            upbring.AddLocation(package, spec.Type, destination);
                        }
                    }

                    // Working with directory
                    if (Directory.Exists(sourcePath))
                    {
                        // Working with directory
                        Uplift.Common.FileSystemUtil.CopyDirectoryWithMeta(sourcePath, destination);
                        if (!PH.SkipPackageStructure)
                        {
                            VCSHandler.HandleDirectory(destination);
                        }

                        bool useGuid = destination.StartsWith("Assets");
                        foreach (var file in Uplift.Common.FileSystemUtil.RecursivelyListFiles(sourcePath, true))
                        {
                            if (useGuid)
                            {
                                TryUpringAddGUID(upbring, file, package, spec.Type, destination);
                            }
                            else
                            {
                                upbring.AddLocation(package, spec.Type, Path.Combine(destination, file));
                            }

                            if (PH.SkipPackageStructure)
                            {
                                VCSHandler.HandleFile(Path.Combine(destination, file));
                            }
                        }
                    }
                }

                upbring.SaveFile();

                if (updateLockfile)
                {
                    LockfileSnapshot snapshot = LoadLockfile();
                    int  index;
                    bool found = false;
                    for (index = 0; index < snapshot.installableDependencies.Length; index++)
                    {
                        if (snapshot.installableDependencies[index].Package.PackageName == package.PackageName)
                        {
                            found = true;
                            break;
                        }
                    }
                    if (found)
                    {
                        snapshot.installableDependencies[index].Package = package;
                    }
                    else
                    {
                        Array.Resize <PackageRepo>(ref snapshot.installableDependencies, snapshot.installableDependencies.Length + 1);
                        snapshot.installableDependencies[snapshot.installableDependencies.Length] = new PackageRepo {
                            Package = package
                        };
                    }
                    GenerateLockfile(snapshot);
                }

                td.Dispose();
                UnityHacks.BuildSettingsEnforcer.EnforceAssetSave();
            }
        }
Пример #30
0
        private LockfileSnapshot LoadLockfile()
        {
            string           pattern = @"([\w\.\-]+)\s\(([\w\.\+!\*]+)\)";
            LockfileSnapshot result  = new LockfileSnapshot();

            using (StreamReader file = new StreamReader(lockfilePath))
            {
                string line = file.ReadLine();
                if (line == null || line != "# UPFILE DEPENDENCIES")
                {
                    throw new FileLoadException("Cannot load Upfile.lock, it is missing the \'UPFILE DEPENDENCIES\' header");
                }

                List <DependencyDefinition> upfileDependencyList = new List <DependencyDefinition>();

                Match match;
                while (!string.IsNullOrEmpty(line = file.ReadLine()))
                {
                    match = Regex.Match(line, pattern);
                    if (!match.Success || match.Groups.Count < 3)
                    {
                        throw new FileLoadException("Cannot load Upfile.lock, the line " + line + " does not match \'package_name (version_requirement)\'");
                    }

                    DependencyDefinition temp = new DependencyDefinition
                    {
                        Name    = match.Groups[1].Value,
                        Version = match.Groups[2].Value
                    };
                    upfileDependencyList.Add(temp);
                }
                result.upfileDependencies = upfileDependencyList.ToArray();

                if (line == null)
                {
                    throw new FileLoadException("Cannot load Upfile.lock, it is incomplete");
                }

                line = file.ReadLine();
                if (line == null || line != "# SOLVED DEPENDENCIES")
                {
                    throw new FileLoadException("Cannot load Upfile.lock, it is missing the \'SOLVED DEPENDENCIES\' header");
                }

                List <PackageRepo> installableList = new List <PackageRepo>();
                line = file.ReadLine();
                PackageList packageList = PackageList.Instance();
                while (!string.IsNullOrEmpty(line))
                {
                    match = Regex.Match(line, pattern);
                    if (!match.Success || match.Groups.Count < 3)
                    {
                        throw new FileLoadException("Cannot load Upfile.lock, the line " + line + " does not match \'package_name (installed_version)\'");
                    }

                    PackageRepo temp = packageList.FindPackageAndRepository(new DependencyDefinition
                    {
                        Name    = match.Groups[1].Value,
                        Version = match.Groups[2].Value + "!" // Check for exact version
                    });

                    if (temp.Package != null && temp.Repository != null)
                    {
                        installableList.Add(temp);
                    }
                    else
                    {
                        installableList.Add(new PackageRepo
                        {
                            Package = new Upset
                            {
                                PackageName    = match.Groups[1].Value,
                                PackageVersion = match.Groups[2].Value
                            }
                        });
                    }
                    // Read the dependencies
                    while ((line = file.ReadLine()) != null && line.StartsWith("\t"))
                    {
                        match = Regex.Match(line, pattern);
                        if (!match.Success || match.Groups.Count < 3)
                        {
                            throw new FileLoadException("Cannot load Upfile.lock, the line " + line + " does not match \'package_name (version_requirement)\'");
                        }
                    }
                }
                result.installableDependencies = installableList.ToArray();
            }

            return(result);
        }