Skip to content

Commit

Permalink
Issue #532
Browse files Browse the repository at this point in the history
  • Loading branch information
AdamNaj committed Jan 11, 2016
1 parent c17d6f2 commit f0796e1
Show file tree
Hide file tree
Showing 4 changed files with 150 additions and 36 deletions.
Expand Up @@ -4,6 +4,7 @@
using System.Linq;
using System.Management.Automation;
using Cognifide.PowerShell.Core.Utility;
using Cognifide.PowerShell.Core.Validation;
using Sitecore.Configuration;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
Expand Down Expand Up @@ -35,6 +36,7 @@ public enum ActionIfExists
public ActionIfExists IfExist { get; set; }

[Parameter]
[AutocompleteSet("Cultures")]
public string[] TargetLanguage { get; set; }

[Parameter]
Expand All @@ -61,7 +63,7 @@ protected override void ProcessItem(Item item)
var targetLanguages = TargetLanguage;
if (targetLanguages == null || targetLanguages.Length == 0)
{
targetLanguages = new[] { Item.Language.Name };
targetLanguages = new[] { item.Language.Name };
}

if (!ShouldProcess(item.GetProviderPath(),
Expand All @@ -87,6 +89,7 @@ protected override void ProcessItem(Item item)
{
foreach (Item childItem in item.Children)
{
childItem.Versions.GetLatestVersion(item.Language);
ProcessItem(childItem);
}
}
Expand Down
129 changes: 108 additions & 21 deletions Cognifide.PowerShell/Commandlets/Data/RemoveItemVersionCommand.cs
@@ -1,30 +1,46 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Cognifide.PowerShell.Core.Utility;
using Sitecore.ContentSearch.Utilities;
using Sitecore.Data.Items;

namespace Cognifide.PowerShell.Commandlets.Data
{
[Cmdlet(VerbsCommon.Remove, "ItemVersion", SupportsShouldProcess = true)]
public class RemoveItemVersionCommand : BaseItemCommand
{
private string confirmMessage;

[Parameter]
public SwitchParameter Recurse { get; set; }

[Alias("Languages")]
[Parameter(ParameterSetName = "Item from Path", Mandatory = true)]
[Parameter(ParameterSetName = "Item from ID", Mandatory = true)]
[Parameter(ParameterSetName = "Item from Pipeline", Mandatory = true)]
[Parameter(ParameterSetName = "Item from Pipeline")]
public override string[] Language { get; set; }

[Alias("ExcludeLanguages")]
[Alias("Versions")]
[Parameter(ParameterSetName = "Item from Path")]
[Parameter(ParameterSetName = "Item from ID")]
[Parameter(ParameterSetName = "Item from Pipeline")]
public string[] Version { get; set; } = new string[0];

[Alias("ExcludeLanguages", "ExcludedLanguages", "ExcludedLanguage")]
[Parameter(ParameterSetName = "Item from Path")]
[Parameter(ParameterSetName = "Item from ID")]
[Parameter(ParameterSetName = "Item from Pipeline")]
public virtual string[] ExcludeLanguage { get; set; }

protected List<WildcardPattern> ExcludeLanguageWildcardPatterns { get; private set; }
protected List<WildcardPattern> VersionPatterns { get; private set; }
protected List<string> ProcessedList { get; private set; }

[Alias("MaxVersions")]
[Parameter]
public int MaxRecentVersions { get; set; } = 0;

protected override void BeginProcessing()
{
Expand All @@ -39,41 +55,112 @@ protected override void BeginProcessing()
language =>
new WildcardPattern(language, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant))
.ToList();

if (Language == null || !Language.Any())
{
Language = new[] {"*"};
}
}

var langsList = Language?.Aggregate((seed, curr) => seed + ", " + curr) ?? "not specified";
var excludedLangsMessage = (ExcludeLanguage == null || ExcludeLanguage.Length == 0)
? ""
: $"excluding {ExcludeLanguage.Aggregate((seed, curr) => seed + ", " + curr)} language(s)";
confirmMessage =
$"R{(Recurse ? "ecursively r" : "")}emove versions for language(s) '{langsList}' {excludedLangsMessage}";

if (Version != null && Version.Any())
{
VersionPatterns =
Version.Select(
version => new WildcardPattern(version, WildcardOptions.IgnoreCase | WildcardOptions.Compiled))
.ToList();
}
else
{
VersionPatterns = new List<WildcardPattern>();
}

base.BeginProcessing();
}

protected override void ProcessItemLanguages(Item item)
{
if (ShouldProcess(item.GetProviderPath(),
string.Format("{0} versions for language(s) '{1}' {2}", (Recurse ? "Recursively remove" : "Remove"),
Language.Aggregate((seed, curr) => seed + ", " + curr),
(ExcludeLanguage == null || ExcludeLanguage.Length == 0)
? ""
: string.Format("excluding {0} language(s)",
ExcludeLanguage.Aggregate((seed, curr) => seed + ", " + curr)))))
ProcessedList = new List<string>();

if (IsParameterSpecified(nameof(Language)) || IsParameterSpecified(nameof(ExcludeLanguage)))
{
foreach (var langItem in item.Versions.GetVersions(true))
foreach (
var langItem in
item.Versions.GetVersions(true)
.Where(
langItem =>
LanguageWildcardPatterns.Any(wildcard => wildcard.IsMatch(langItem.Language.Name)))
.Where(
langItem =>
!ExcludeLanguageWildcardPatterns.Any(
wildcard => wildcard.IsMatch(langItem.Language.Name))))
{
if (LanguageWildcardPatterns.Any(wildcard => wildcard.IsMatch(langItem.Language.Name)))
{
if (!ExcludeLanguageWildcardPatterns.Any(wildcard => wildcard.IsMatch(langItem.Language.Name)))
{
langItem.Versions.RemoveAll(false);
}
}
TrimVersions(langItem);
}
}
else
{
TrimVersions(item);
}
if (Recurse)
{
foreach (Item child in item.Children)
{
ProcessItemLanguages(child);
}
if (Recurse)
}
}

private void TrimVersions(Item langItem)
{
// no specific version number provided
if (!Version.Any())
{
// version number trimming
if (IsParameterSpecified(nameof(MaxRecentVersions)))
{
foreach (Item child in item.Children)
if (langItem.Versions.Count > MaxRecentVersions)
{
ProcessItemLanguages(child);
langItem.Versions.GetVersionNumbers()
.Take(langItem.Versions.Count - MaxRecentVersions)
.ForEach(verNo => RemoveVersion(langItem.Versions[verNo]));
}
}
else
{
//just remove the piped version
RemoveVersion(langItem);
}
}
else
{
// versions specified - check if matching filter
if (VersionPatterns.Any(wildcard => wildcard.IsMatch(langItem.Version.Number.ToString())))
{
RemoveVersion(langItem);
}
}
}

private void RemoveVersion(Item item)
{
var itemSig = $"{item.Database}:{item.ID}/{item.Language}#{item.Version}";
if (!ProcessedList.Contains(itemSig))
{
ProcessedList.Add(itemSig);
if (
ShouldProcess(
item.GetProviderPath() + ", Lang:" + item.Language.Name + ", Ver:" + item.Version.Number,
confirmMessage))
{
item.Versions.RemoveVersion();
}
}
}

Expand Down
Expand Up @@ -3,23 +3,24 @@
Creates a version of the item in a new language based on an existing language version.
.DESCRIPTION
Creates a version of the item in a new language based on an existing language version.
Creates a new version of the item in a specified language based on an existing language/version.
Based on parameters you can make the command bahave differently when a version in the target language already exists and define which fields if any should be copied over from the original language.
.PARAMETER Recurse
Process the item and all of its children.
.PARAMETER IfExist
Default vaule is Append
Accepts one of 3 pretty self explanatory actions:
- Append - [Default] if language version exists create a new version with values copied from the original language
- Skip - if language version exists don't do anything
- Append - if language version exists create a new version with values copied from the original language
- OverwriteLatest - if language version exists overwrite the last version with values copied from the original language
.PARAMETER TargetLanguage
Language or a list of languages that should be created
.PARAMETER DoNotCopyFields
Creates a version in the target language but does not copy field values from the original language
Creates a new version in the target language but does not copy field values from the original language
.PARAMETER IgnoredFields
List of fields that should not be copied over from original item. As an example, use "__Security" if you don't want the new version to have the same restrictions as the original version.
Expand All @@ -38,7 +39,7 @@
- __Reminder text
.PARAMETER Item
The item to be processed.
The item / version to be processed.
.PARAMETER Path
Path to the item to be processed - additionally specify Language parameter to fetch different item language than the current user language.
Expand All @@ -65,20 +66,27 @@
https://github.com/SitecorePowerShell/Console/
.LINK
Remove-ItemLanguage
Remove-ItemVersion
.LINK
New-Item
.LINK
https://gist.github.com/AdamNaj/b36ea095e3668c22c07e
.EXAMPLE
# Translate the Home Item from English to US and Polish leaving the "Title" field blank. If a version exists don't do anything
PS master:\> Add-ItemLanguage -Path "master:\content\home" -Language "en" -TargetLanguage "pl-pl", "en-us" -IfExist Skip -IgnoredFields "Title"
PS master:\> Add-ItemVersion -Path "master:\content\home" -Language "en" -TargetLanguage "pl-pl", "en-us" -IfExist Skip -IgnoredFields "Title"
.EXAMPLE
Add a Japanese version to /sitecore/content/home item in the master database based on itself
PS master:\> Add-ItemVersion -Path "master:\content\home" -Language ja-JP -IfExist Append
.EXAMPLE
# Translate the children of Home item (but only those of Template Name "Sample Item") from English to US and Polish. If a version exists create a new version for that language. Display results in a table listing item name, language and created version number.
Get-ChildItem "master:\content\home" -Language "en" -Recurse | `
Where-Object { $_.TemplateName -eq "Sample Item" } | `
Add-ItemLanguage -TargetLanguage "pl-pl" -IfExist Append | `
Add-ItemVersion -TargetLanguage "pl-pl" -IfExist Append | `
Format-Table Name, Language, Version -auto
#>
@@ -1,9 +1,9 @@
<#
.SYNOPSIS
Removes Language from a single item or a branch of items
Removes Language/Version from a single item or a branch of items
.DESCRIPTION
Removes Language version from a an Item either sent from pipeline or defined with Path or ID. A single language or a list of languages can be defined using the Language parameter.
Removes Language/Version from a an Item either sent from pipeline or defined with Path or ID. A single language or a list of languages can be defined using the Language parameter.
Language parameter supports globbing so you can delete whole language groups using wildcards.
Expand All @@ -15,15 +15,23 @@
A single language or a list of languages can be defined using the parameter.
Language parameter supports globbing so you can delete whole language groups using wildcards.
.PARAMETER Version
Version(s) that should be deleted form the provided item(s).
A single version or a list of versions can be defined using the parameter.
Version parameter supports globbing so you can delete whole version groups using wildcards.
.PARAMETER ExcludeLanguage
Language(s) that should NOT be deleted form the provided item(s).
A single language or a list of languages can be defined using the parameter.
Language parameter supports globbing so you can delete whole language groups using wildcards.
If Language parameter is not is not specified but ExcludeLanguage is provided, the default value of "*" is assumed for Language parameter.
.PARAMETER MaxRecentVersions
If provided - trims the selected language to value specified by this parameter.
.PARAMETER Item
The item to be processed.
The item/version to be processed. You can pipe a specific version of the item for it to be removed.
.PARAMETER Path
Path to the item to be processed - can work with Language parameter to narrow the publication scope.
Expand All @@ -46,20 +54,28 @@
https://github.com/SitecorePowerShell/Console/
.LINK
Add-ItemLanguage
Add-ItemVersion
.LINK
Remove-Item
.LINK
https://gist.github.com/AdamNaj/b36ea095e3668c22c07e
.EXAMPLE
# Remove Polish and Spanish language from /sitecore/content/home item in the master database
PS master:\> Remove-ItemLanguage -Path master:\content\home -Language "pl-pl", "es-es"
PS master:\> Remove-ItemVersion -Path master:\content\home -Language "pl-pl", "es-es"
.EXAMPLE
# Remove all english based languages defined in /sitecore/content/home item and all of its children in the master database
PS master:\> Remove-ItemLanguage -Path master:\content\home -Language "en-*" -Recurse
PS master:\> Remove-ItemVersion -Path master:\content\home -Language "en-*" -Recurse
.EXAMPLE
# Remove all languages except those that are "en" based defined in /sitecore/content/home item and all of its children in the master database
PS master:\> Remove-ItemLanguage -Path master:\content\home -ExcludeLanguage "en*" -Recurse
PS master:\> Remove-ItemVersion -Path master:\content\home -ExcludeLanguage "en*" -Recurse
.EXAMPLE
# Trim all languages to 3 latest versions for /sitecore/content/home item and all of its children in the master database
PS master:\> Remove-ItemVersion -Path master:\content\home -Language * -Recurse
#>

0 comments on commit f0796e1

Please sign in to comment.