示例#1
0
        public override bool Execute()
        {
            try
            {
                var matcher = new Matcher().AddInclude(Pattern);
                var assets  = new List <ITaskItem>();
                var assetsByRelativePath = new Dictionary <string, List <ITaskItem> >();

                for (var i = 0; i < Candidates.Length; i++)
                {
                    var candidate          = Candidates[i];
                    var candidateMatchPath = GetCandidateMatchPath(candidate);
                    var match = matcher.Match(candidateMatchPath);
                    if (!match.HasMatches)
                    {
                        Log.LogMessage("Rejected asset '{0}' for pattern '{1}'", candidateMatchPath, Pattern);
                        continue;
                    }

                    Log.LogMessage("Accepted asset '{0}' for pattern '{1}' with relative path '{2}'", candidateMatchPath, Pattern, match.Files.Single().Stem);

                    var candidateRelativePath = StaticWebAsset.Normalize(match.Files.Single().Stem);

                    var asset = new StaticWebAsset
                    {
                        Identity               = candidate.GetMetadata("FullPath"),
                        SourceId               = SourceId,
                        SourceType             = StaticWebAsset.SourceTypes.Discovered,
                        ContentRoot            = ContentRoot,
                        BasePath               = BasePath,
                        RelativePath           = candidateRelativePath,
                        AssetMode              = StaticWebAsset.AssetModes.All,
                        CopyToOutputDirectory  = candidate.GetMetadata(nameof(StaticWebAsset.CopyToOutputDirectory)),
                        CopyToPublishDirectory = candidate.GetMetadata(nameof(StaticWebAsset.CopyToPublishDirectory))
                    };

                    asset.ApplyDefaults();
                    asset.Normalize();

                    var assetItem = asset.ToTaskItem();

                    assetItem.SetMetadata("OriginalItemSpec", candidate.ItemSpec);
                    assets.Add(assetItem);

                    UpdateAssetKindIfNecessary(assetsByRelativePath, candidateRelativePath, assetItem);
                    if (Log.HasLoggedErrors)
                    {
                        return(false);
                    }
                }

                DiscoveredStaticWebAssets = assets.ToArray();
            }
            catch (Exception ex)
            {
                Log.LogError(ex.Message);
            }

            return(!Log.HasLoggedErrors);
        }
        public override bool Execute()
        {
            try
            {
                var originalAssets = new List <ITaskItem>();
                var updatedAssets  = new List <ITaskItem>();
                for (var i = 0; i < Assets.Length; i++)
                {
                    var candidate = Assets[i];
                    if (!StaticWebAsset.SourceTypes.IsPackage(candidate.GetMetadata(nameof(StaticWebAsset.SourceType))))
                    {
                        continue;
                    }

                    originalAssets.Add(candidate);
                    updatedAssets.Add(StaticWebAsset.FromV1TaskItem(candidate).ToTaskItem());
                }

                OriginalAssets = originalAssets.ToArray();
                UpdatedAssets  = updatedAssets.ToArray();
            }
            catch (Exception ex)
            {
                Log.LogError(ex.ToString());
            }

            return(!Log.HasLoggedErrors);
        }
        public override bool Execute()
        {
            try
            {
                Log.LogMessage("Using path prefix '{0}'", PathPrefix);
                AssetsWithTargetPath = new TaskItem[Assets.Length];

                for (var i = 0; i < Assets.Length; i++)
                {
                    var staticWebAsset = StaticWebAsset.FromTaskItem(Assets[i]);
                    var result         = staticWebAsset.ToTaskItem();
                    var targetPath     = staticWebAsset.ComputeTargetPath(
                        PathPrefix,
                        UseAlternatePathDirectorySeparator ? Path.AltDirectorySeparatorChar : Path.DirectorySeparatorChar);

                    result.SetMetadata("TargetPath", targetPath);

                    AssetsWithTargetPath[i] = result;
                }
            }
            catch (Exception ex)
            {
                Log.LogError(ex.Message);
            }

            return(!Log.HasLoggedErrors);
        }
示例#4
0
        // Iterate over the list of assets with the same Identity and choose the one closest to the asset kind we've been given:
        // The given asset kind here will always be Build or Publish.
        // We need to iterate over the assets, the moment we detect one asset for our specific kind, we return that asset
        // While we iterate over the list of assets we keep any asset of the `All` kind we find on a variable.
        // * If we find a more specific asset, we will ignore it in favor of the specific one.
        // * If we don't find a more specfic (Build or Publish) asset we will return the `All` asset.
        // We assume that the manifest is correct and don't try to deal with errors at this level, if for some reason we find more
        // than one type of asset we will just return all of them.
        // One exception to this is the `All` kind of assets, where we will just return the first two we find. The reason for it is
        // to avoid having to allocate a buffer to collect all the `All` assets.
        internal static IEnumerable <StaticWebAsset> ChooseNearestAssetKind(IEnumerable <StaticWebAsset> group, string assetKind)
        {
            StaticWebAsset allKindAssetCandidate = null;

            var ignoreAllKind = false;

            foreach (var item in group)
            {
                if (item.HasKind(assetKind))
                {
                    ignoreAllKind = true;

                    yield return(item);
                }
                else if (!ignoreAllKind && item.IsBuildAndPublish())
                {
                    if (allKindAssetCandidate != null)
                    {
                        yield return(allKindAssetCandidate);

                        yield return(item);

                        yield break;
                    }
                    allKindAssetCandidate = item;
                }
            }

            if (!ignoreAllKind)
            {
                yield return(allKindAssetCandidate);
            }
        }
示例#5
0
        public override bool Execute()
        {
            try
            {
                Log.LogMessage(MessageImportance.Low, "Using path prefix '{0}'", PathPrefix);
                AssetsWithTargetPath = new TaskItem[Assets.Length];

                for (var i = 0; i < Assets.Length; i++)
                {
                    var staticWebAsset = StaticWebAsset.FromTaskItem(Assets[i]);
                    var result         = staticWebAsset.ToTaskItem();
                    var targetPath     = staticWebAsset.ComputeTargetPath(
                        PathPrefix,
                        UseAlternatePathDirectorySeparator ? Path.AltDirectorySeparatorChar : Path.DirectorySeparatorChar);

                    if (AdjustPathsForPack && string.IsNullOrEmpty(Path.GetExtension(targetPath)))
                    {
                        targetPath = Path.GetDirectoryName(targetPath);
                    }

                    result.SetMetadata("TargetPath", targetPath);

                    AssetsWithTargetPath[i] = result;
                }
            }
            catch (Exception ex)
            {
                Log.LogError(ex.Message);
            }

            return(!Log.HasLoggedErrors);
        }
示例#6
0
        public override bool Execute()
        {
            try
            {
                var currentProjectAssets = Assets
                                           .Where(asset => StaticWebAsset.HasSourceId(asset, Source))
                                           .Select(StaticWebAsset.FromTaskItem)
                                           .GroupBy(
                    a => a.ComputeTargetPath("", '/'),
                    (key, group) => (key, StaticWebAsset.ChooseNearestAssetKind(group, AssetKind)));

                var resultAssets = new List <StaticWebAsset>();
                foreach (var(key, group) in currentProjectAssets)
                {
                    if (!TryGetUniqueAsset(group, out var selected))
                    {
                        if (selected == null)
                        {
                            Log.LogMessage(MessageImportance.Low, "No compatible asset found for '{0}'", key);
                            continue;
                        }
                        else
                        {
                            Log.LogError("More than one compatible asset found for '{0}'.", selected.Identity);
                            return(false);
                        }
                    }

                    if (!selected.IsForReferencedProjectsOnly())
                    {
                        resultAssets.Add(selected);
                    }
                    else
                    {
                        Log.LogMessage(MessageImportance.Low, "Skipping asset '{0}' because it is for referenced projects only.", selected.Identity);
                    }
                }

                StaticWebAssets = resultAssets
                                  .Select(a => a.ToTaskItem())
                                  .Concat(Assets.Where(asset => !StaticWebAsset.HasSourceId(asset, Source)))
                                  .ToArray();
            }
            catch (Exception ex)
            {
                Log.LogError(ex.ToString());
            }

            return(!Log.HasLoggedErrors);
        }
示例#7
0
        private (string identity, bool computed) ComputeCandidateIdentity(ITaskItem candidate, string contentRoot, string relativePath, Matcher matcher)
        {
            var candidateFullPath = Path.GetFullPath(candidate.GetMetadata("FullPath"));

            if (contentRoot == null)
            {
                Log.LogMessage(MessageImportance.Low, "Identity for candidate '{0}' is '{1}' because content root is not defined.", candidate.ItemSpec, candidateFullPath);
                return(candidateFullPath, false);
            }

            var normalizedContentRoot = StaticWebAsset.NormalizeContentRootPath(contentRoot);

            if (candidateFullPath.StartsWith(normalizedContentRoot))
            {
                Log.LogMessage(MessageImportance.Low, "Identity for candidate '{0}' is '{1}' because it starts with content root '{2}'.", candidate.ItemSpec, candidateFullPath, normalizedContentRoot);
                return(candidateFullPath, false);
            }
            else
            {
                // We want to support assets that are part of the source codebase but that might get transformed during the build or
                // publish processes, so we want to allow defining these assets by setting up a different content root path from their
                // original location in the project. For example the asset can be wwwroot\my-prod-asset.js, the content root can be
                // obj\transform and the final asset identity can be <<FullPathTo>>\obj\transform\my-prod-asset.js
                var matchResult = matcher?.Match(candidate.ItemSpec);
                if (matcher == null)
                {
                    // If no relative path pattern was specified, we are going to suggest that the identity is `%(ContentRoot)\RelativePath\OriginalFileName`
                    // We don't want to use the relative path file name since multiple assets might map to that and conflicts might arise.
                    // Alternatively, we could be explicit here and support ContentRootSubPath to indicate where it needs to go.
                    var identitySubPath  = Path.GetDirectoryName(relativePath);
                    var itemSpecFileName = Path.GetFileName(candidateFullPath);
                    var finalIdentity    = Path.Combine(normalizedContentRoot, identitySubPath, itemSpecFileName);
                    Log.LogMessage(MessageImportance.Low, "Identity for candidate '{0}' is '{1}' because it did not start with the content root '{2}'", candidate.ItemSpec, finalIdentity, normalizedContentRoot);
                    return(finalIdentity, true);
                }
                else if (!matchResult.HasMatches)
                {
                    Log.LogMessage(MessageImportance.Low, "Identity for candidate '{0}' is '{1}' because it didn't match the relative path pattern", candidate.ItemSpec, candidateFullPath);
                    return(candidateFullPath, false);
                }
                else
                {
                    var stem          = matchResult.Files.Single().Stem;
                    var assetIdentity = Path.GetFullPath(Path.Combine(normalizedContentRoot, stem));
                    Log.LogMessage(MessageImportance.Low, "Computed identity '{0}' for candidate '{1}'", assetIdentity, candidate.ItemSpec);

                    return(assetIdentity, true);
                }
            }
        }
示例#8
0
        private string GetCandidateMatchPath(ITaskItem candidate)
        {
            var computedPath = StaticWebAsset.ComputeAssetRelativePath(candidate, out var property);

            if (property != null)
            {
                Log.LogMessage(
                    "{0} '{1}' found for candidate '{2}' and will be used for matching.",
                    property,
                    computedPath,
                    candidate.ItemSpec);
            }

            return(computedPath);
        }
示例#9
0
        private bool TryGetUniqueAsset(IEnumerable <StaticWebAsset> candidates, out StaticWebAsset selected)
        {
            selected = null;
            foreach (var asset in candidates)
            {
                if (selected != null)
                {
                    return(false);
                }

                selected = asset;
            }

            return(selected != null);
        }
        public override bool Execute()
        {
            try
            {
                var manifest = ComputeDevelopmentManifest(
                    Assets.Select(a => StaticWebAsset.FromTaskItem(a)),
                    DiscoveryPatterns.Select(ComputeDiscoveryPattern));

                PersistManifest(manifest);
            }
            catch (Exception ex)
            {
                Log.LogError(ex.ToString());
                Log.LogErrorFromException(ex);
            }
            return(!Log.HasLoggedErrors);
        }
示例#11
0
        private string GetCandidateMatchPath(ITaskItem candidate)
        {
            var relativePath = candidate.GetMetadata("RelativePath");

            if (!string.IsNullOrEmpty(relativePath))
            {
                var normalizedPath = StaticWebAsset.Normalize(relativePath, allowEmpyPath: true);
                Log.LogMessage(MessageImportance.Low, "RelativePath '{0}' normalized to '{1}' found for candidate '{2}' and will be used for matching.", relativePath, normalizedPath, candidate.ItemSpec);
                return(normalizedPath);
            }

            var targetPath = candidate.GetMetadata("TargetPath");

            if (!string.IsNullOrEmpty(targetPath))
            {
                var normalizedPath = StaticWebAsset.Normalize(targetPath, allowEmpyPath: true);
                Log.LogMessage(MessageImportance.Low, "TargetPath '{0}' normalized to '{1}' found for candidate '{2}' and will be used for matching.", targetPath, normalizedPath, candidate.ItemSpec);
                return(normalizedPath);
            }

            var linkPath = candidate.GetMetadata("Link");

            if (!string.IsNullOrEmpty(linkPath))
            {
                var normalizedPath = StaticWebAsset.Normalize(linkPath, allowEmpyPath: true);
                Log.LogMessage(MessageImportance.Low, "Link '{0}'  normalized to '{1}' found for candidate '{2}' and will be used for matching.", linkPath, normalizedPath, candidate.ItemSpec);

                return(linkPath);
            }

            var normalizedContentRoot = StaticWebAsset.NormalizeContentRootPath(string.IsNullOrEmpty(candidate.GetMetadata(nameof(StaticWebAsset.ContentRoot))) ?
                                                                                ContentRoot :
                                                                                candidate.GetMetadata(nameof(StaticWebAsset.ContentRoot)));

            var normalizedAssetPath = Path.GetFullPath(candidate.GetMetadata("FullPath"));

            if (normalizedAssetPath.StartsWith(normalizedContentRoot))
            {
                return(normalizedAssetPath.Substring(normalizedContentRoot.Length));
            }
            else
            {
                return(candidate.ItemSpec);
            }
        }
示例#12
0
        internal static StaticWebAsset FromProperties(
            string identity,
            string sourceId,
            string sourceType,
            string basePath,
            string relativePath,
            string contentRoot,
            string assetKind,
            string assetMode,
            string assetRole,
            string relatedAsset,
            string assetTraitName,
            string assetTraitValue,
            string copyToOutputDirectory,
            string copyToPublishDirectory,
            string originalItemSpec)
        {
            var result = new StaticWebAsset
            {
                Identity               = identity,
                SourceId               = sourceId,
                SourceType             = sourceType,
                ContentRoot            = contentRoot,
                BasePath               = basePath,
                RelativePath           = relativePath,
                AssetKind              = assetKind,
                AssetMode              = assetMode,
                AssetRole              = assetRole,
                RelatedAsset           = relatedAsset,
                AssetTraitName         = assetTraitName,
                AssetTraitValue        = assetTraitValue,
                CopyToOutputDirectory  = copyToOutputDirectory,
                CopyToPublishDirectory = copyToPublishDirectory,
                OriginalItemSpec       = originalItemSpec
            };

            result.ApplyDefaults();

            result.Normalize();
            result.Validate();

            return(result);
        }
示例#13
0
        private bool ShouldIncludeAssetAsReference(StaticWebAsset candidate, out string reason)
        {
            if (!StaticWebAssetsManifest.ManifestModes.ShouldIncludeAssetAsReference(candidate, ProjectMode))
            {
                reason = string.Format(
                    "Skipping candidate asset '{0}' because project mode is '{1}' and asset mode is '{2}'",
                    candidate.Identity,
                    ProjectMode,
                    candidate.AssetMode);
                return(false);
            }

            reason = string.Format(
                "Accepted candidate asset '{0}' because project mode is '{1}' and asset mode is '{2}'",
                candidate.Identity,
                ProjectMode,
                candidate.AssetMode);

            return(true);
        }
示例#14
0
        public override bool Execute()
        {
            try
            {
                var assets = Assets.OrderBy(a => a.GetMetadata("FullPath")).Select(StaticWebAsset.FromTaskItem);

                var assetsByTargetPath = assets.GroupBy(a => a.ComputeTargetPath("", '/'), StringComparer.OrdinalIgnoreCase);
                foreach (var group in assetsByTargetPath)
                {
                    if (!StaticWebAsset.ValidateAssetGroup(group.Key, group.ToArray(), ManifestType, out var reason))
                    {
                        Log.LogError(reason);
                        return(false);
                    }
                }

                var discoveryPatterns = DiscoveryPatterns
                                        .OrderBy(a => a.ItemSpec)
                                        .Select(StaticWebAssetsManifest.DiscoveryPattern.FromTaskItem)
                                        .ToArray();

                var referencedProjectsConfiguration = ReferencedProjectsConfigurations.OrderBy(a => a.ItemSpec)
                                                      .Select(StaticWebAssetsManifest.ReferencedProjectConfiguration.FromTaskItem)
                                                      .ToArray();

                PersistManifest(
                    StaticWebAssetsManifest.Create(
                        Source,
                        BasePath,
                        Mode,
                        ManifestType,
                        referencedProjectsConfiguration,
                        discoveryPatterns,
                        assets.ToArray()));
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex, showStackTrace: true, showDetail: true, file: null);
            }
            return(!Log.HasLoggedErrors);
        }
示例#15
0
        internal static bool ValidateAssetGroup(string path, StaticWebAsset [] group, string assetKind, out string reason)
        {
            StaticWebAsset prototypeItem = null;
            StaticWebAsset build         = null;
            StaticWebAsset publish       = null;
            StaticWebAsset all           = null;

            foreach (var item in group)
            {
                prototypeItem ??= item;
                if (!prototypeItem.HasSourceId(item.SourceId))
                {
                    reason = $"Conflicting assets with the same target path '{path}'. For assets '{prototypeItem}' and '{item}' from different projects.";
                    return(false);
                }

                build ??= item.IsBuildOnly() ? item : build;
                if (build != null && item.IsBuildOnly() && !ReferenceEquals(build, item))
                {
                    reason = $"Conflicting assets with the same target path '{path}'. For 'Build' assets '{build}' and '{item}'.";
                    return(false);
                }

                publish ??= item.IsPublishOnly() ? item : publish;
                if (publish != null && item.IsPublishOnly() && !ReferenceEquals(publish, item))
                {
                    reason = $"Conflicting assets with the same target path '{path}'. For 'Publish' assets '{publish}' and '{item}'.";
                    return(false);
                }

                all ??= item.IsBuildAndPublish() ? item : all;
                if (all != null && item.IsBuildAndPublish() && !ReferenceEquals(all, item))
                {
                    reason = $"Conflicting assets with the same target path '{path}'. For 'All' assets '{all}' and '{item}'.";
                    return(false);
                }
            }
            reason = null;
            return(true);
        }
示例#16
0
 static bool AreKindsCompatible(StaticWebAsset asset, StaticWebAsset existing) =>
 // We could have done this with asset.IsPublishOnly() ^ existing.IsPublishOnly(), but this way is more clear.
 (asset.AssetKind, existing.AssetKind) switch
示例#17
0
 internal bool IsCurrentProjectAsset(StaticWebAsset asset) => asset.HasSourceId(Source);
示例#18
0
        public override bool Execute()
        {
            try
            {
                var manifests = new List <StaticWebAssetsManifest>();
                ReadCandidateManifests(manifests);

                if (Log.HasLoggedErrors)
                {
                    return(false);
                }

                var existingAssets = ExistingAssets
                                     .ToDictionary(a => (a.GetMetadata("AssetKind"), a.ItemSpec), a => StaticWebAsset.FromTaskItem(a));

                var staticWebAssets   = new Dictionary <(string, string), StaticWebAsset>();
                var discoveryPatterns = new Dictionary <string, StaticWebAssetsManifest.DiscoveryPattern>();
                foreach (var manifest in manifests)
                {
                    MergeDiscoveryPatterns(discoveryPatterns, manifest);
                    if (Log.HasLoggedErrors)
                    {
                        break;
                    }

                    MergeStaticWebAssets(staticWebAssets, existingAssets, manifest);

                    if (Log.HasLoggedErrors)
                    {
                        break;
                    }
                }

                StaticWebAssets   = staticWebAssets.Select(a => a.Value.ToTaskItem()).ToArray();
                DiscoveryPatterns = discoveryPatterns.Select(d => d.Value.ToTaskItem()).ToArray();
            }
            catch (Exception ex)
            {
                Log.LogError(ex.ToString());
            }

            return(!Log.HasLoggedErrors);
        }
示例#19
0
        public override bool Execute()
        {
            try
            {
                var results        = new List <ITaskItem>();
                var copyCandidates = new List <ITaskItem>();

                var matcher = !string.IsNullOrEmpty(RelativePathPattern) ? new Matcher().AddInclude(RelativePathPattern) : null;
                var filter  = !string.IsNullOrEmpty(RelativePathFilter) ? new Matcher().AddInclude(RelativePathFilter) : null;
                for (var i = 0; i < CandidateAssets.Length; i++)
                {
                    var candidate             = CandidateAssets[i];
                    var relativePathCandidate = GetCandidateMatchPath(candidate);
                    if (matcher != null)
                    {
                        var match = matcher.Match(relativePathCandidate);
                        if (match.HasMatches)
                        {
                            var newRelativePathCandidate = match.Files.Single().Stem;
                            Log.LogMessage(
                                MessageImportance.Low,
                                "The relative path '{0}' matched the pattern '{1}'. Replacing relative path with '{2}'.",
                                relativePathCandidate,
                                RelativePathPattern,
                                newRelativePathCandidate);

                            relativePathCandidate = newRelativePathCandidate;
                        }
                    }

                    if (filter != null && !filter.Match(relativePathCandidate).HasMatches)
                    {
                        Log.LogMessage(
                            MessageImportance.Low,
                            "Skipping '{0}' because the relative path '{1}' did not match the filter '{2}'.",
                            candidate.ItemSpec,
                            relativePathCandidate,
                            RelativePathFilter);

                        continue;
                    }

                    var sourceId               = ComputePropertyValue(candidate, nameof(StaticWebAsset.SourceId), SourceId);
                    var sourceType             = ComputePropertyValue(candidate, nameof(StaticWebAsset.SourceType), SourceType);
                    var basePath               = ComputePropertyValue(candidate, nameof(StaticWebAsset.BasePath), BasePath);
                    var contentRoot            = ComputePropertyValue(candidate, nameof(StaticWebAsset.ContentRoot), ContentRoot);
                    var assetKind              = ComputePropertyValue(candidate, nameof(StaticWebAsset.AssetKind), AssetKind, isRequired: false);
                    var assetMode              = ComputePropertyValue(candidate, nameof(StaticWebAsset.AssetMode), AssetMode);
                    var assetRole              = ComputePropertyValue(candidate, nameof(StaticWebAsset.AssetRole), AssetRole);
                    var relatedAsset           = ComputePropertyValue(candidate, nameof(StaticWebAsset.RelatedAsset), RelatedAsset, !StaticWebAsset.AssetRoles.IsPrimary(assetRole));
                    var assetTraitName         = ComputePropertyValue(candidate, nameof(StaticWebAsset.AssetTraitName), AssetTraitName, !StaticWebAsset.AssetRoles.IsPrimary(assetRole));
                    var assetTraitValue        = ComputePropertyValue(candidate, nameof(StaticWebAsset.AssetTraitValue), AssetTraitValue, !StaticWebAsset.AssetRoles.IsPrimary(assetRole));
                    var copyToOutputDirectory  = ComputePropertyValue(candidate, nameof(StaticWebAsset.CopyToOutputDirectory), CopyToOutputDirectory);
                    var copyToPublishDirectory = ComputePropertyValue(candidate, nameof(StaticWebAsset.CopyToPublishDirectory), CopyToPublishDirectory);
                    var originalItemSpec       = ComputePropertyValue(
                        candidate,
                        nameof(StaticWebAsset.OriginalItemSpec),
                        PropertyOverrides == null || PropertyOverrides.Length == 0 ? candidate.ItemSpec : candidate.GetMetadata("OriginalItemSpec"));

                    // If we are not able to compute the value based on an existing value or a default, we produce an error and stop.
                    if (Log.HasLoggedErrors)
                    {
                        break;
                    }

                    // We ignore the content root for publish only assets since it doesn't matter.
                    var contentRootPrefix = StaticWebAsset.AssetKinds.IsPublish(assetKind) ? null : contentRoot;
                    var(identity, computed) = ComputeCandidateIdentity(candidate, contentRootPrefix, relativePathCandidate, matcher);

                    if (computed)
                    {
                        copyCandidates.Add(new TaskItem(candidate.ItemSpec, new Dictionary <string, string>
                        {
                            ["TargetPath"] = identity
                        }));
                    }

                    var asset = StaticWebAsset.FromProperties(
                        identity,
                        sourceId,
                        sourceType,
                        basePath,
                        relativePathCandidate,
                        contentRoot,
                        assetKind,
                        assetMode,
                        assetRole,
                        relatedAsset,
                        assetTraitName,
                        assetTraitValue,
                        copyToOutputDirectory,
                        copyToPublishDirectory,
                        originalItemSpec);

                    var item = asset.ToTaskItem();

                    results.Add(item);
                }

                Assets         = results.ToArray();
                CopyCandidates = copyCandidates.ToArray();
            }
            catch (Exception ex)
            {
                Log.LogError(ex.ToString());
            }

            return(!Log.HasLoggedErrors);
        }
        public override bool Execute()
        {
            var copyToOutputFolder   = new List <ITaskItem>();
            var normalizedOutputPath = StaticWebAsset.NormalizeContentRootPath(Path.GetFullPath(OutputPath));

            try
            {
                foreach (var asset in Assets.Select(StaticWebAsset.FromTaskItem))
                {
                    string fileOutputPath = null;
                    if (!(asset.IsDiscovered() || asset.IsComputed()))
                    {
                        Log.LogMessage(MessageImportance.Low, "Skipping asset '{0}' since source type is '{1}'", asset.Identity, asset.SourceType);
                        continue;
                    }

                    if (asset.IsForReferencedProjectsOnly())
                    {
                        Log.LogMessage(MessageImportance.Low, "Skipping asset '{0}' since asset mode is '{1}'", asset.Identity, asset.AssetMode);
                    }

                    if (asset.ShouldCopyToOutputDirectory())
                    {
                        // We have an asset we want to copy to the output folder.
                        fileOutputPath = Path.Combine(normalizedOutputPath, asset.RelativePath);
                        string source = null;
                        if (asset.IsComputed())
                        {
                            if (asset.Identity.StartsWith(normalizedOutputPath, StringComparison.Ordinal))
                            {
                                Log.LogMessage(MessageImportance.Low, "Source for asset '{0}' is '{1}' since the identity points to the output path.", asset.Identity, asset.OriginalItemSpec);
                                source = asset.OriginalItemSpec;
                            }
                            else if (File.Exists(asset.Identity))
                            {
                                Log.LogMessage(MessageImportance.Low, "Source for asset '{0}' is '{0}' since the asset exists.", asset.Identity);
                                source = asset.Identity;
                            }
                            else
                            {
                                Log.LogMessage(MessageImportance.Low, "Source for asset '{0}' is '{1}' since the asset does not exist.", asset.Identity, asset.OriginalItemSpec);
                                source = asset.OriginalItemSpec;
                            }
                        }
                        else
                        {
                            source = asset.Identity;
                        }

                        copyToOutputFolder.Add(new TaskItem(source, new Dictionary <string, string>
                        {
                            ["OriginalItemSpec"]      = asset.Identity,
                            ["TargetPath"]            = fileOutputPath,
                            ["CopyToOutputDirectory"] = asset.CopyToOutputDirectory
                        }));
                    }
                    else
                    {
                        Log.LogMessage(MessageImportance.Low, "Skipping asset '{0}' since copy to output directory option is '{1}'", asset.Identity, asset.CopyToOutputDirectory);
                    }
                }

                AssetsToCopy = copyToOutputFolder.ToArray();
            }
            catch (Exception ex)
            {
                Log.LogError(ex.ToString());
            }

            return(!Log.HasLoggedErrors);
        }
示例#21
0
        public override bool Execute()
        {
            try
            {
                var existingAssets = Assets
                                     .Where(asset => StaticWebAsset.HasSourceId(asset, Source))
                                     .Select(StaticWebAsset.FromTaskItem)
                                     .GroupBy(
                    a => a.ComputeTargetPath("", '/'),
                    (key, group) => (key, StaticWebAsset.ChooseNearestAssetKind(group, AssetKind)));

                var resultAssets = new List <StaticWebAsset>();
                foreach (var(key, group) in existingAssets)
                {
                    if (!TryGetUniqueAsset(group, out var selected))
                    {
                        if (selected == null)
                        {
                            Log.LogMessage("No compatible asset found for '{0}'", key);
                            continue;
                        }
                        else
                        {
                            Log.LogError("More than one compatible asset found for '{0}'.", selected.Identity);
                            return(false);
                        }
                    }

                    if (ShouldIncludeAssetAsReference(selected, out var reason))
                    {
                        selected.SourceType = StaticWebAsset.SourceTypes.Project;
                        resultAssets.Add(selected);
                    }
                    Log.LogMessage(reason);
                }

                var patterns = new List <StaticWebAssetsManifest.DiscoveryPattern>();
                if (Patterns != null)
                {
                    foreach (var pattern in Patterns)
                    {
                        if (!StaticWebAssetsManifest.DiscoveryPattern.HasSourceId(pattern, Source))
                        {
                            Log.LogMessage("Skipping pattern '{0}' because is not defined in the current project.", pattern.ItemSpec);
                        }
                        else
                        {
                            Log.LogMessage("Including pattern '{0}' because is defined in the current project.", pattern.ToString());
                            patterns.Add(StaticWebAssetsManifest.DiscoveryPattern.FromTaskItem(pattern));
                        }
                    }
                }

                StaticWebAssets   = resultAssets.Select(a => a.ToTaskItem()).ToArray();
                DiscoveryPatterns = patterns.Select(p => p.ToTaskItem()).ToArray();
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex, showStackTrace: true, showDetail: true, file: null);
            }

            return(!Log.HasLoggedErrors);
        }
示例#22
0
 internal bool HasSourceId(string source) =>
 StaticWebAsset.HasSourceId(SourceId, source);