commanderclient

package
v0.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DeepLDefaultBaseURL = "https://api.deepl.com/v2"
	DeepLDefaultTimeout = 10 * time.Second
)

DeepL API constants

View Source
const (
	StatusDraft     = "draft"
	StatusPublished = "published"
	StatusChanged   = "changed"
)

Publishing status constants

View Source
const (
	OperationCreate    = "create"
	OperationUpsert    = "upsert"
	OperationUpdate    = "update"
	OperationDelete    = "delete"
	OperationPublish   = "publish"
	OperationUnpublish = "unpublish"
)

Migration operation constants

Variables

This section is empty.

Functions

func CreateFieldUpdate

func CreateFieldUpdate(fieldName string, locale Locale, value any) map[string]any

CreateFieldUpdate creates a field update for a specific field and locale

func FixURI added in v0.3.0

func FixURI(input string) string

FixURI strips diacritics, lowercases, and replaces non-alphanumeric characters with dashes, producing a clean URL-safe slug.

func Init

func Init(config *Config) (*MigrationClient, *Logger, error)

Init creates a ready-to-use migration client with logger and loaded space model

func MatchCase added in v0.3.0

func MatchCase(input, reference string) string

func PrintResults

func PrintResults(results []MigrationResult)

PrintResults prints migration results

func PrintStats

func PrintStats(stats *MigrationStats)

PrintStats prints migration statistics

func ProcessHyperlinks(
	entity Entity,
	fieldName string,
	locale Locale,
	resolver HyperlinkResolver,
) error

ProcessHyperlinks finds all hyperlinks in a RichText field and applies the resolver to each hyperlink's URI. This is useful for fixing URLs during content migration, such as converting German URLs to English equivalents.

The function modifies the entity's field in-place for the specified locale. Only RichText fields are supported; string fields will return an error.

Example:

resolver := func(uri string) (string, error) {
    // Convert German URLs to English
    if strings.HasPrefix(uri, "/de/") {
        return strings.Replace(uri, "/de/", "/en/", 1), nil
    }
    return uri, nil
}
err := ProcessHyperlinks(entry, "content", cc.Locale("en"), resolver)

func ProcessHyperlinksInFields added in v0.3.0

func ProcessHyperlinksInFields(
	entity Entity,
	fieldNames []string,
	locale Locale,
	resolver HyperlinkResolver,
) error

ProcessHyperlinksInFields processes hyperlinks in multiple fields. This is a convenience function for processing several RichText fields at once. Errors are collected and returned as a combined error; processing continues even if some fields fail.

func ToLowerURL added in v0.3.0

func ToLowerURL(input string) string

func TranslateField added in v0.3.0

func TranslateField(
	entity Entity,
	fieldName string,
	sourceLocale Locale,
	targetLocale Locale,
	translate TranslateFunc,
) (billedCharacters int, err error)

TranslateField translates a field value from source to target locale. It automatically handles different field types:

  • String fields (Symbol, Text): translated directly
  • RichText fields: all text nodes are extracted, translated individually, and reassembled

The translate function is called once for each text chunk. For RichText fields with many text nodes, consider using TranslateFieldBatch for efficiency. Returns the total number of billed characters for the translation.

func TranslateFieldBatch added in v0.3.0

func TranslateFieldBatch(
	entity Entity,
	fieldName string,
	sourceLocale Locale,
	targetLocale Locale,
	translateBatch TranslateBatchFunc,
) (billedCharacters int, err error)

TranslateFieldBatch translates a field value using batch translation. This is more efficient for RichText fields when using APIs that support batch requests, as all text nodes are translated in a single API call.

For simple string fields, this behaves the same as TranslateField but wraps the single text in a batch call. Returns the total number of billed characters for the translation.

func TranslateFieldBatchIfEmpty added in v0.3.0

func TranslateFieldBatchIfEmpty(
	entity Entity,
	fieldName string,
	sourceLocale Locale,
	targetLocale Locale,
	translateBatch TranslateBatchFunc,
) (billedCharacters int, err error)

TranslateFieldBatchIfEmpty is like TranslateFieldIfEmpty but uses batch translation. Returns the total number of billed characters for the translation (0 if skipped).

func TranslateFieldIfEmpty added in v0.3.0

func TranslateFieldIfEmpty(
	entity Entity,
	fieldName string,
	sourceLocale Locale,
	targetLocale Locale,
	translate TranslateFunc,
) (billedCharacters int, err error)

TranslateFieldIfEmpty translates only if the target locale field is empty or nil. This is useful for incremental translation where you don't want to re-translate already translated content. Returns the total number of billed characters for the translation (0 if skipped).

Types

type AssetEntity

type AssetEntity struct {
	Asset  *contentful.Asset
	Client *MigrationClient
}

AssetEntity wraps a Contentful asset

func (*AssetEntity) GetContentType

func (ae *AssetEntity) GetContentType() string

func (*AssetEntity) GetCreatedAt

func (ae *AssetEntity) GetCreatedAt() time.Time

func (*AssetEntity) GetDescription

func (ae *AssetEntity) GetDescription(locale Locale) string

func (*AssetEntity) GetFieldValue

func (ae *AssetEntity) GetFieldValue(fieldName string, locale Locale) any

func (*AssetEntity) GetFieldValueAsBool

func (ae *AssetEntity) GetFieldValueAsBool(fieldName string, locale Locale) bool

func (*AssetEntity) GetFieldValueAsFloat64

func (ae *AssetEntity) GetFieldValueAsFloat64(fieldName string, locale Locale) float64

func (*AssetEntity) GetFieldValueAsReference

func (ae *AssetEntity) GetFieldValueAsReference(fieldName string, locale Locale) *contentful.Entry

func (*AssetEntity) GetFieldValueAsReferencedEntities

func (ae *AssetEntity) GetFieldValueAsReferencedEntities(fieldName string, locale Locale) *EntityCollection

func (*AssetEntity) GetFieldValueAsReferencedEntity

func (ae *AssetEntity) GetFieldValueAsReferencedEntity(fieldName string, locale Locale) (Entity, bool)

func (*AssetEntity) GetFieldValueAsReferences

func (ae *AssetEntity) GetFieldValueAsReferences(fieldName string, locale Locale) []*contentful.Entry

func (*AssetEntity) GetFieldValueAsString

func (ae *AssetEntity) GetFieldValueAsString(fieldName string, locale Locale) string

func (*AssetEntity) GetFieldValueInto

func (ae *AssetEntity) GetFieldValueInto(fieldName string, locale Locale, target any) error

func (*AssetEntity) GetFieldValueWithFallback

func (ae *AssetEntity) GetFieldValueWithFallback(fieldName string, locale Locale, defaultLocale Locale) any

func (*AssetEntity) GetFields

func (ae *AssetEntity) GetFields() map[string]any

func (*AssetEntity) GetFile

func (ae *AssetEntity) GetFile(locale Locale) *contentful.File

func (*AssetEntity) GetID

func (ae *AssetEntity) GetID() string

func (*AssetEntity) GetParents added in v0.3.2

func (ae *AssetEntity) GetParents(contentTypes []string) *EntityCollection

GetParents returns all entities that reference this asset. If contentTypes is non-nil, only parents matching those content types are returned.

func (*AssetEntity) GetPublishingStatus

func (ae *AssetEntity) GetPublishingStatus() string

func (*AssetEntity) GetSys

func (ae *AssetEntity) GetSys() *contentful.Sys

func (*AssetEntity) GetTitle

func (ae *AssetEntity) GetTitle(locale Locale) string

func (*AssetEntity) GetType

func (ae *AssetEntity) GetType() string

func (*AssetEntity) GetUpdatedAt

func (ae *AssetEntity) GetUpdatedAt() time.Time

func (*AssetEntity) GetVersion

func (ae *AssetEntity) GetVersion() int

func (*AssetEntity) IsAsset

func (ae *AssetEntity) IsAsset() bool

func (*AssetEntity) IsEntry

func (ae *AssetEntity) IsEntry() bool

func (*AssetEntity) IsPublished

func (ae *AssetEntity) IsPublished() bool

func (*AssetEntity) SetFieldValue

func (ae *AssetEntity) SetFieldValue(fieldName string, locale Locale, value any)

type CollectionStats

type CollectionStats struct {
	TotalCount             int
	EntryCount             int
	AssetCount             int
	ContentTypeCounts      map[string]int
	PublishingStatusCounts map[string]int
	TypeCounts             map[string]int
	OldestEntity           time.Time
	NewestEntity           time.Time
}

CollectionStats provides statistics about a collection

type Config

type Config struct {
	CMAToken    string
	SpaceID     string
	Environment string
	Verbose     bool
}

Config holds configuration for the migration library

func LoadConfigFromEnv

func LoadConfigFromEnv() *Config

LoadConfigFromEnv loads configuration from environment variables

func (*Config) ValidateConfig

func (c *Config) ValidateConfig() error

ValidateConfig validates the configuration

type DeepLAPIError added in v0.3.0

type DeepLAPIError struct {
	StatusCode int
	Message    string
}

DeepLAPIError represents an API error

func (*DeepLAPIError) Error added in v0.3.0

func (e *DeepLAPIError) Error() string

type DeepLClient added in v0.3.0

type DeepLClient struct {
	// contains filtered or unexported fields
}

DeepLClient is the DeepL API client

func NewDeepLClient added in v0.3.0

func NewDeepLClient(authKey string, options ...DeepLClientOption) *DeepLClient

NewDeepLClient creates a new DeepL API client

func (*DeepLClient) Translate added in v0.3.0

Translate sends a translation request to the DeepL API

func (*DeepLClient) TranslateText added in v0.3.0

func (c *DeepLClient) TranslateText(text string, targetLang DeepLTargetLang, sourceLang DeepLSourceLang) (string, int, error)

TranslateText is a convenience function for translating a single text string. Returns the translated text and the number of billed characters.

type DeepLClientOption added in v0.3.0

type DeepLClientOption func(*DeepLClient)

DeepLClientOption configures a DeepLClient

func WithDeepLBaseURL added in v0.3.0

func WithDeepLBaseURL(baseURL string) DeepLClientOption

WithDeepLBaseURL sets a custom base URL (useful for testing or proxies)

func WithDeepLTimeout added in v0.3.0

func WithDeepLTimeout(timeout time.Duration) DeepLClientOption

WithDeepLTimeout sets a custom HTTP timeout

type DeepLFormality added in v0.3.0

type DeepLFormality string

DeepLFormality controls translation formality

const (
	DeepLFormalityDefault    DeepLFormality = "default"
	DeepLFormalityMore       DeepLFormality = "more"
	DeepLFormalityLess       DeepLFormality = "less"
	DeepLFormalityPreferMore DeepLFormality = "prefer_more"
	DeepLFormalityPreferLess DeepLFormality = "prefer_less"
)

type DeepLModelType added in v0.3.0

type DeepLModelType string

DeepLModelType controls the translation model

const (
	DeepLModelTypeQualityOptimized       DeepLModelType = "quality_optimized"
	DeepLModelTypePreferQualityOptimized DeepLModelType = "prefer_quality_optimized"
	DeepLModelTypeLatencyOptimized       DeepLModelType = "latency_optimized"
)

type DeepLSourceLang added in v0.3.0

type DeepLSourceLang string

DeepLSourceLang represents supported source languages

const (
	DeepLSourceDE DeepLSourceLang = "DE" // German
	DeepLSourceEN DeepLSourceLang = "EN" // English
	DeepLSourceFR DeepLSourceLang = "FR" // French
	DeepLSourceES DeepLSourceLang = "ES" // Spanish
	DeepLSourceIT DeepLSourceLang = "IT" // Italian
	DeepLSourceNL DeepLSourceLang = "NL" // Dutch
	DeepLSourcePL DeepLSourceLang = "PL" // Polish
	DeepLSourcePT DeepLSourceLang = "PT" // Portuguese
	DeepLSourceRU DeepLSourceLang = "RU" // Russian
	DeepLSourceJA DeepLSourceLang = "JA" // Japanese
	DeepLSourceZH DeepLSourceLang = "ZH" // Chinese
)

type DeepLSplitSentences added in v0.3.0

type DeepLSplitSentences string

DeepLSplitSentences controls sentence splitting behavior

const (
	DeepLSplitSentencesNone       DeepLSplitSentences = "0"          // No splitting
	DeepLSplitSentencesDefault    DeepLSplitSentences = "1"          // Split on punctuation and newlines
	DeepLSplitSentencesNoNewlines DeepLSplitSentences = "nonewlines" // Split on punctuation only
)

type DeepLTargetLang added in v0.3.0

type DeepLTargetLang string

DeepLTargetLang represents supported target languages

const (
	DeepLTargetDE   DeepLTargetLang = "DE"    // German
	DeepLTargetENGB DeepLTargetLang = "EN-GB" // English (British)
	DeepLTargetENUS DeepLTargetLang = "EN-US" // English (American)
	DeepLTargetFR   DeepLTargetLang = "FR"    // French
	DeepLTargetES   DeepLTargetLang = "ES"    // Spanish
	DeepLTargetIT   DeepLTargetLang = "IT"    // Italian
	DeepLTargetNL   DeepLTargetLang = "NL"    // Dutch
	DeepLTargetPL   DeepLTargetLang = "PL"    // Polish
	DeepLTargetPTBR DeepLTargetLang = "PT-BR" // Portuguese (Brazilian)
	DeepLTargetPTPT DeepLTargetLang = "PT-PT" // Portuguese (European)
	DeepLTargetRU   DeepLTargetLang = "RU"    // Russian
	DeepLTargetJA   DeepLTargetLang = "JA"    // Japanese
	DeepLTargetZH   DeepLTargetLang = "ZH"    // Chinese (simplified)
)

type DeepLTranslateRequest added in v0.3.0

type DeepLTranslateRequest struct {
	Text               []string            `json:"text"`                  // Required: Text to translate
	SourceLang         DeepLSourceLang     `json:"source_lang,omitempty"` // Optional: Source language
	TargetLang         DeepLTargetLang     `json:"target_lang"`           // Required: Target language
	Context            string              `json:"context,omitempty"`     // Optional: Context for translation
	ShowBilledChars    *bool               `json:"show_billed_characters,omitempty"`
	SplitSentences     DeepLSplitSentences `json:"split_sentences,omitempty"`
	PreserveFormatting *bool               `json:"preserve_formatting,omitempty"`
	Formality          DeepLFormality      `json:"formality,omitempty"`
	ModelType          DeepLModelType      `json:"model_type,omitempty"`
	GlossaryID         string              `json:"glossary_id,omitempty"`
}

DeepLTranslateRequest represents a translation request

type DeepLTranslateResponse added in v0.3.0

type DeepLTranslateResponse struct {
	Translations []DeepLTranslation `json:"translations"`
}

DeepLTranslateResponse represents the API response

type DeepLTranslation added in v0.3.0

type DeepLTranslation struct {
	DetectedSourceLanguage string         `json:"detected_source_language"`
	Text                   string         `json:"text"`
	BilledCharacters       int            `json:"billed_characters,omitempty"`
	ModelTypeUsed          DeepLModelType `json:"model_type_used,omitempty"`
}

DeepLTranslation represents a single translation result

type DeepLTranslator added in v0.3.0

type DeepLTranslator struct {
	Client *DeepLClient
	Source SourceLocale
	Target TargetLocale
}

DeepLTranslator provides field translation using the DeepL API. It combines Contentful locale mapping with DeepL language settings.

func NewDeepLTranslator added in v0.3.0

func NewDeepLTranslator(client *DeepLClient, source SourceLocale, target TargetLocale) *DeepLTranslator

NewDeepLTranslator creates a new DeepLTranslator with the given client and locale settings.

func (*DeepLTranslator) Translate added in v0.3.0

func (d *DeepLTranslator) Translate(text string) (string, int, error)

Translate translates a single text string using the configured languages. Returns the translated text and the number of billed characters.

func (*DeepLTranslator) TranslateBatch added in v0.3.0

func (d *DeepLTranslator) TranslateBatch(texts []string) ([]string, int, error)

TranslateBatch translates multiple texts using the configured languages. Returns the translated texts and the total number of billed characters.

func (*DeepLTranslator) TranslateField added in v0.3.0

func (d *DeepLTranslator) TranslateField(entity Entity, fieldName string) (int, error)

TranslateField translates a field value from source to target locale. It automatically handles different field types:

  • String fields (Symbol, Text): translated directly
  • RichText fields: all text nodes are extracted, translated individually, and reassembled

Returns the total number of billed characters for the translation.

func (*DeepLTranslator) TranslateFieldBatch added in v0.3.0

func (d *DeepLTranslator) TranslateFieldBatch(entity Entity, fieldName string) (int, error)

TranslateFieldBatch translates a field value using batch translation. This is more efficient for RichText fields as all text nodes are translated in a single API call. Returns the total number of billed characters for the translation.

func (*DeepLTranslator) TranslateFieldBatchIfEmpty added in v0.3.0

func (d *DeepLTranslator) TranslateFieldBatchIfEmpty(entity Entity, fieldName string) (int, error)

TranslateFieldBatchIfEmpty is like TranslateFieldIfEmpty but uses batch translation. Returns the total number of billed characters for the translation (0 if skipped).

func (*DeepLTranslator) TranslateFieldIfEmpty added in v0.3.0

func (d *DeepLTranslator) TranslateFieldIfEmpty(entity Entity, fieldName string) (int, error)

TranslateFieldIfEmpty translates only if the target locale field is empty or nil. This is useful for incremental translation where you don't want to re-translate already translated content. Returns the total number of billed characters for the translation (0 if skipped).

type Entity

type Entity interface {
	// GetID returns the unique identifier of the entity
	GetID() string

	// GetType returns the type of entity ("Entry" or "Asset")
	GetType() string

	// GetContentType returns the content type ID for entries, empty string for assets
	GetContentType() string

	// GetCreatedAt returns the creation timestamp
	GetCreatedAt() time.Time

	// GetUpdatedAt returns the last update timestamp
	GetUpdatedAt() time.Time

	// GetVersion returns the current version number
	GetVersion() int

	// IsPublished returns true if the entity is published
	IsPublished() bool

	// GetPublishingStatus returns the publishing status of the entity
	GetPublishingStatus() string

	// GetFields returns the raw fields data (always locale maps)
	GetFields() map[string]any

	// GetFieldValue returns the value of a field for a specific locale
	GetFieldValue(fieldName string, locale Locale) any

	// GetFieldValueWithFallback returns the field value for the specified locale, falling back to defaultLocale if not found
	GetFieldValueWithFallback(fieldName string, locale Locale, defaultLocale Locale) any

	// GetFieldValueAsString returns the field value as string if found and is string type
	GetFieldValueAsString(fieldName string, locale Locale) string

	// GetFieldValueAsFloat64 returns the field value as float64 if found and is float64 type
	GetFieldValueAsFloat64(fieldName string, locale Locale) float64

	// GetFieldValueAsBool returns the field value as bool if found and is bool type
	GetFieldValueAsBool(fieldName string, locale Locale) bool

	// GetFieldValueAsReference unmarshals the field value into a contentful.Entry
	GetFieldValueAsReference(fieldName string, locale Locale) *contentful.Entry

	// GetFieldValueAsReferencedEntity returns the actual entity referenced by the field value
	GetFieldValueAsReferencedEntity(fieldName string, locale Locale) (Entity, bool)

	// GetFieldValueAsReferencedEntities returns a collection of entities referenced by the field value
	// Broken references are silently skipped and not included in the returned collection
	GetFieldValueAsReferencedEntities(fieldName string, locale Locale) *EntityCollection

	// GetFieldValueAsReferences returns a slice of contentful.Entry from the field value
	GetFieldValueAsReferences(fieldName string, locale Locale) []*contentful.Entry

	// GetFieldValueInto unmarshals the field value into a target variable using a pointer
	// Note: This method is primarily useful for entries with variable field structures
	GetFieldValueInto(fieldName string, locale Locale, target any) error

	// GetTitle returns the title of the entity for the specified locale
	GetTitle(locale Locale) string

	// GetDescription returns the description of the entity for the specified locale
	GetDescription(locale Locale) string

	// GetFile returns the file information of the entity for the specified locale
	GetFile(locale Locale) *contentful.File

	// SetFieldValue sets the value of a field for a specific locale
	SetFieldValue(fieldName string, locale Locale, value any)

	// GetSys returns the system metadata
	GetSys() *contentful.Sys

	// IsEntry returns true if this entity is an Entry
	IsEntry() bool

	// IsAsset returns true if this entity is an Asset
	IsAsset() bool

	// GetParents returns all entities that reference this entity.
	// If contentTypes is non-nil, only parents matching those content types are returned.
	GetParents(contentTypes []string) *EntityCollection
}

Entity represents either a Contentful entry or asset

type EntityCollection

type EntityCollection struct {
	// contains filtered or unexported fields
}

EntityCollection represents a collection of entities with filtering capabilities

func NewEntityCollection

func NewEntityCollection(entities []Entity) *EntityCollection

NewEntityCollection creates a new entity collection from a slice of entities

func (*EntityCollection) Count

func (ec *EntityCollection) Count() int

Count returns the number of entities in the collection

func (*EntityCollection) CountByContentType

func (ec *EntityCollection) CountByContentType() map[string]int

CountByContentType returns counts by content type

func (*EntityCollection) CountByPublishingStatus

func (ec *EntityCollection) CountByPublishingStatus() map[string]int

CountByPublishingStatus returns counts by publishing status

func (*EntityCollection) ExtractContentTypes

func (ec *EntityCollection) ExtractContentTypes() []string

ExtractContentTypes returns all unique content types

func (*EntityCollection) ExtractFieldValues

func (ec *EntityCollection) ExtractFieldValues(fieldName string, locale Locale) []any

ExtractFieldValues extracts a specific field from all entities for a specific locale

func (*EntityCollection) ExtractFieldValuesWithFallback

func (ec *EntityCollection) ExtractFieldValuesWithFallback(fieldName string, locale Locale, defaultLocale Locale) []any

ExtractFieldValuesWithFallback extracts a specific field from all entities for a specific locale with fallback

func (*EntityCollection) ExtractFields

func (ec *EntityCollection) ExtractFields(fieldName string) []any

ExtractFields extracts a specific field from all entities

func (*EntityCollection) ExtractIDs

func (ec *EntityCollection) ExtractIDs() []string

ExtractIDs returns all entity IDs

func (*EntityCollection) Filter

func (ec *EntityCollection) Filter(filters ...EntityFilter) *EntityCollection

Filter applies additional filters to the collection

func (*EntityCollection) ForEach

func (ec *EntityCollection) ForEach(fn func(Entity))

ForEach applies a function to each entity in the collection

func (*EntityCollection) ForEachConcurrent added in v0.3.0

func (ec *EntityCollection) ForEachConcurrent(concurrency int, fn func(Entity))

ForEachConcurrent applies a function to each entity concurrently with a specified concurrency level

func (*EntityCollection) Get

func (ec *EntityCollection) Get() []Entity

Get returns all entities in the collection

func (*EntityCollection) GetByID

func (ec *EntityCollection) GetByID(id string) (Entity, bool)

GetByID returns an entity by ID, if it exists in the collection

func (*EntityCollection) GetStats

func (ec *EntityCollection) GetStats() *CollectionStats

GetStats returns comprehensive statistics about the collection

func (*EntityCollection) GroupBy

func (ec *EntityCollection) GroupBy(keyFn func(Entity) string) map[string][]Entity

GroupBy groups entities by a key function

func (*EntityCollection) GroupByContentType

func (ec *EntityCollection) GroupByContentType() map[string]*EntityCollection

GroupByContentType groups entities by content type

func (*EntityCollection) GroupByPublishingStatus

func (ec *EntityCollection) GroupByPublishingStatus() map[string]*EntityCollection

GroupByPublishingStatus groups entities by publishing status

func (*EntityCollection) Limit

func (ec *EntityCollection) Limit(n int) *EntityCollection

Limit returns a new collection with at most n entities

func (*EntityCollection) Skip

func (ec *EntityCollection) Skip(n int) *EntityCollection

Skip returns a new collection skipping the first n entities

func (*EntityCollection) ToDeleteOperations

func (ec *EntityCollection) ToDeleteOperations() []MigrationOperation

ToDeleteOperations creates delete operations for all entities

func (*EntityCollection) ToMigrationOperations

func (ec *EntityCollection) ToMigrationOperations(operation string) []MigrationOperation

ToMigrationOperations converts entities to migration operations

func (*EntityCollection) ToPublishOperations

func (ec *EntityCollection) ToPublishOperations() []MigrationOperation

ToPublishOperations creates publish operations for all entities

func (*EntityCollection) ToUnpublishOperations

func (ec *EntityCollection) ToUnpublishOperations() []MigrationOperation

ToUnpublishOperations creates unpublish operations for all entities

func (*EntityCollection) ToUpdateOperations

func (ec *EntityCollection) ToUpdateOperations() []MigrationOperation

ToUpdateOperations creates update operations for all entities

func (*EntityCollection) Transform

func (ec *EntityCollection) Transform(fn func(Entity) Entity) *EntityCollection

Transform applies a transformation function to each entity and returns a new collection

type EntityFilter

type EntityFilter func(Entity) bool

EntityFilter is a function that filters entities

func FilterByContentType

func FilterByContentType(contentTypes ...string) EntityFilter

FilterByContentType returns a filter for specific content types

func FilterByCreatedAfter

func FilterByCreatedAfter(t time.Time) EntityFilter

FilterByCreatedAfter returns a filter for entities created after a specific time

func FilterByFieldContains

func FilterByFieldContains(fieldName, substring string) EntityFilter

FilterByFieldContains returns a filter for entities where a field contains a substring

func FilterByFieldContainsWithLocale

func FilterByFieldContainsWithLocale(fieldName string, locale Locale, substring string) EntityFilter

FilterByFieldContainsWithLocale returns a filter for entities where a field contains a substring for a specific locale

func FilterByFieldExists

func FilterByFieldExists(fieldName string) EntityFilter

FilterByFieldExists returns a filter for entities that have a specific field

func FilterByFieldExistsWithLocale

func FilterByFieldExistsWithLocale(fieldName string, locale Locale) EntityFilter

FilterByFieldExistsWithLocale returns a filter for entities that have a specific field for a locale

func FilterByFieldValue

func FilterByFieldValue(fieldName string, expectedValue any) EntityFilter

FilterByFieldValue returns a filter for entities with specific field values

func FilterByFieldValueWithFallback

func FilterByFieldValueWithFallback(fieldName string, locale Locale, defaultLocale Locale, expectedValue any) EntityFilter

FilterByFieldValueWithFallback returns a filter for entities with specific field values using fallback locale

func FilterByFieldValueWithLocale

func FilterByFieldValueWithLocale(fieldName string, locale Locale, expectedValue any) EntityFilter

FilterByFieldValueWithLocale returns a filter for entities with specific field values for a locale

func FilterByID

func FilterByID(entityID string) EntityFilter

FilterByID returns a filter for entities matching an ID pattern

func FilterByLocaleAvailability

func FilterByLocaleAvailability(requiredLocales []Locale) EntityFilter

FilterByLocaleAvailability returns a filter for entities that have content in specific locales

func FilterByType

func FilterByType(entityType string) EntityFilter

FilterByType returns a filter for entity types (Entry/Asset)

func FilterByUpdatedAfter

func FilterByUpdatedAfter(t time.Time) EntityFilter

FilterByUpdatedAfter returns a filter for entities updated after a specific time

func FilterDrafts

func FilterDrafts() EntityFilter

FilterDrafts returns a filter for draft entities

func FilterPublished

func FilterPublished() EntityFilter

FilterPublished returns a filter for published entities

type EntryEntity

type EntryEntity struct {
	Entry  *contentful.Entry
	Client *MigrationClient
}

EntryEntity wraps a Contentful entry

func (*EntryEntity) GetContentType

func (ee *EntryEntity) GetContentType() string

func (*EntryEntity) GetCreatedAt

func (ee *EntryEntity) GetCreatedAt() time.Time

func (*EntryEntity) GetDescription

func (ee *EntryEntity) GetDescription(locale Locale) string

func (*EntryEntity) GetFieldValue

func (ee *EntryEntity) GetFieldValue(fieldName string, locale Locale) any

func (*EntryEntity) GetFieldValueAsBool

func (ee *EntryEntity) GetFieldValueAsBool(fieldName string, locale Locale) bool

func (*EntryEntity) GetFieldValueAsFloat64

func (ee *EntryEntity) GetFieldValueAsFloat64(fieldName string, locale Locale) float64

func (*EntryEntity) GetFieldValueAsReference

func (ee *EntryEntity) GetFieldValueAsReference(fieldName string, locale Locale) *contentful.Entry

func (*EntryEntity) GetFieldValueAsReferencedEntities

func (ee *EntryEntity) GetFieldValueAsReferencedEntities(fieldName string, locale Locale) *EntityCollection

func (*EntryEntity) GetFieldValueAsReferencedEntity

func (ee *EntryEntity) GetFieldValueAsReferencedEntity(fieldName string, locale Locale) (Entity, bool)

func (*EntryEntity) GetFieldValueAsReferences

func (ee *EntryEntity) GetFieldValueAsReferences(fieldName string, locale Locale) []*contentful.Entry

func (*EntryEntity) GetFieldValueAsString

func (ee *EntryEntity) GetFieldValueAsString(fieldName string, locale Locale) string

func (*EntryEntity) GetFieldValueInto

func (ee *EntryEntity) GetFieldValueInto(fieldName string, locale Locale, target any) error

func (*EntryEntity) GetFieldValueWithFallback

func (ee *EntryEntity) GetFieldValueWithFallback(fieldName string, locale Locale, defaultLocale Locale) any

func (*EntryEntity) GetFields

func (ee *EntryEntity) GetFields() map[string]any

func (*EntryEntity) GetFile

func (ee *EntryEntity) GetFile(locale Locale) *contentful.File

func (*EntryEntity) GetID

func (ee *EntryEntity) GetID() string

func (*EntryEntity) GetParents added in v0.3.2

func (ee *EntryEntity) GetParents(contentTypes []string) *EntityCollection

GetParents returns all entities that reference this entry. If contentTypes is non-nil, only parents matching those content types are returned.

func (*EntryEntity) GetPublishingStatus

func (ee *EntryEntity) GetPublishingStatus() string

func (*EntryEntity) GetSys

func (ee *EntryEntity) GetSys() *contentful.Sys

func (*EntryEntity) GetTitle

func (ee *EntryEntity) GetTitle(locale Locale) string

func (*EntryEntity) GetType

func (ee *EntryEntity) GetType() string

func (*EntryEntity) GetUpdatedAt

func (ee *EntryEntity) GetUpdatedAt() time.Time

func (*EntryEntity) GetVersion

func (ee *EntryEntity) GetVersion() int

func (*EntryEntity) IsAsset

func (ee *EntryEntity) IsAsset() bool

func (*EntryEntity) IsEntry

func (ee *EntryEntity) IsEntry() bool

func (*EntryEntity) IsPublished

func (ee *EntryEntity) IsPublished() bool

func (*EntryEntity) SetFieldValue

func (ee *EntryEntity) SetFieldValue(fieldName string, locale Locale, value any)

type HyperlinkResolver added in v0.3.0

type HyperlinkResolver func(uri string) (newUri string, err error)

HyperlinkResolver receives a URI and returns the replacement URI. Return the original URI unchanged if no modification is needed. Return an error to abort processing.

type Locale

type Locale string

Locale represents a Contentful locale code

func GetDefaultLocale

func GetDefaultLocale(locales []LocaleInfo) Locale

GetDefaultLocale returns the default locale from a list of locales

func GetLocaleCodes

func GetLocaleCodes(locales []LocaleInfo) []Locale

GetLocaleCodes returns all locale codes from locale info

func (Locale) IsValid

func (l Locale) IsValid() bool

IsValidLocale checks if a locale code is valid

func (Locale) String

func (l Locale) String() string

String returns the string representation of the locale

type LocaleInfo

type LocaleInfo struct {
	Code         Locale `json:"code"`
	Name         string `json:"name"`
	FallbackCode Locale `json:"fallbackCode"`
	Optional     bool   `json:"optional"`
	Default      bool   `json:"default"`
}

LocaleInfo represents information about a Contentful locale

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger provides structured logging for migrations

func NewLogger

func NewLogger(verbose bool) *Logger

NewLogger creates a new logger

func (*Logger) Debug

func (l *Logger) Debug(format string, args ...any)

Debug logs a debug message (only if verbose is enabled)

func (*Logger) Error

func (l *Logger) Error(format string, args ...any)

Error logs an error message

func (*Logger) Info

func (l *Logger) Info(format string, args ...any)

Info logs an info message

func (*Logger) Warn

func (l *Logger) Warn(format string, args ...any)

Warn logs a warning message

type MigrationClient

type MigrationClient struct {
	// contains filtered or unexported fields
}

MigrationClient provides a high-level interface for Contentful migrations

func (*MigrationClient) FilterEntities

func (mc *MigrationClient) FilterEntities(filters ...EntityFilter) *EntityCollection

FilterEntities applies filters to entities and returns a collection

func (*MigrationClient) GetAllEntities

func (mc *MigrationClient) GetAllEntities() *EntityCollection

GetAllEntities returns all cached entities

func (*MigrationClient) GetAssets

func (mc *MigrationClient) GetAssets() *EntityCollection

GetAssets returns all asset entities

func (*MigrationClient) GetCMA

func (mc *MigrationClient) GetCMA() *contentful.Contentful

GetCMA returns the underlying CMA client

func (*MigrationClient) GetConcurrency added in v0.3.0

func (mc *MigrationClient) GetConcurrency() int

GetConcurrency returns the concurrency level for batch operations

func (*MigrationClient) GetDefaultLocale

func (mc *MigrationClient) GetDefaultLocale() Locale

GetDefaultLocale returns the default locale for the space

func (*MigrationClient) GetEntitiesByContentType

func (mc *MigrationClient) GetEntitiesByContentType(contentType string) *EntityCollection

GetEntitiesByContentType returns entities filtered by content type

func (*MigrationClient) GetEntity

func (mc *MigrationClient) GetEntity(id string) (Entity, bool)

GetEntity retrieves an entity by ID from cache

func (*MigrationClient) GetEntries

func (mc *MigrationClient) GetEntries() *EntityCollection

GetEntries returns all entry entities

func (*MigrationClient) GetEnvironment

func (mc *MigrationClient) GetEnvironment() string

GetEnvironment returns the environment

func (*MigrationClient) GetLocaleCodes

func (mc *MigrationClient) GetLocaleCodes() []Locale

GetLocaleCodes returns all locale codes for the space

func (*MigrationClient) GetLocales

func (mc *MigrationClient) GetLocales() []LocaleInfo

GetLocales returns the locales for the space

func (*MigrationClient) GetSpaceID

func (mc *MigrationClient) GetSpaceID() string

GetSpaceID returns the space ID

func (*MigrationClient) GetSpaceModel

func (mc *MigrationClient) GetSpaceModel() *SpaceModel

GetSpaceModel returns the cached space model

func (*MigrationClient) GetStats

func (mc *MigrationClient) GetStats() *MigrationStats

GetStats returns migration statistics

func (*MigrationClient) LoadSpaceModel

func (mc *MigrationClient) LoadSpaceModel(ctx context.Context, logger *Logger) error

LoadSpaceModel loads and caches the entire space model

func (*MigrationClient) RefreshEntity

func (mc *MigrationClient) RefreshEntity(ctx context.Context, id string) error

RefreshEntity updates a single entity in the cache

func (*MigrationClient) RemoveEntity

func (mc *MigrationClient) RemoveEntity(id string)

RemoveEntity removes an entity from the cache

func (*MigrationClient) SetConcurrency added in v0.3.0

func (mc *MigrationClient) SetConcurrency(n int)

SetConcurrency sets the concurrency level for batch operations

type MigrationExecutor

type MigrationExecutor struct {
	// contains filtered or unexported fields
}

MigrationExecutor handles the execution of migration operations

func NewMigrationExecutor

func NewMigrationExecutor(client *MigrationClient, options *MigrationOptions) *MigrationExecutor

NewMigrationExecutor creates a new migration executor

func (*MigrationExecutor) ExecuteBatch

func (me *MigrationExecutor) ExecuteBatch(ctx context.Context, operations []MigrationOperation) []MigrationResult

ExecuteBatch executes multiple operations in batch with concurrency

func (*MigrationExecutor) ExecuteOperation

func (me *MigrationExecutor) ExecuteOperation(ctx context.Context, op *MigrationOperation) *MigrationResult

ExecuteOperation executes a single migration operation

func (*MigrationExecutor) GetErrorCount

func (me *MigrationExecutor) GetErrorCount() int

GetErrorCount returns the number of failed operations

func (*MigrationExecutor) GetResults

func (me *MigrationExecutor) GetResults() []MigrationResult

GetResults returns all migration results

func (*MigrationExecutor) GetSuccessCount

func (me *MigrationExecutor) GetSuccessCount() int

GetSuccessCount returns the number of successful operations

type MigrationOperation

type MigrationOperation struct {
	EntityID  string
	Operation string // Use Operation* constants from types.go
	Entity    Entity
}

MigrationOperation represents a migration operation to be performed

func CreateUpdateOperation

func CreateUpdateOperation(entityID string, entity Entity) *MigrationOperation

CreateUpdateOperation creates a migration operation

type MigrationOptions

type MigrationOptions struct {
	DryRun  bool
	Confirm bool
}

MigrationOptions configures migration behavior

func DefaultMigrationOptions

func DefaultMigrationOptions() *MigrationOptions

DefaultMigrationOptions returns sensible defaults

type MigrationResult

type MigrationResult struct {
	EntityID    string
	Operation   string
	Success     bool
	Error       error
	ProcessedAt time.Time
}

MigrationResult represents the result of a migration operation

type MigrationStats

type MigrationStats struct {
	TotalEntities    int
	ProcessedEntries int
	ProcessedAssets  int
	Errors           int
	StartTime        time.Time
	EndTime          time.Time
	Duration         time.Duration
}

MigrationStats tracks migration statistics

func (*MigrationStats) Printf

func (ms *MigrationStats) Printf() string

Printf returns a formatted string with migration statistics

type RichTextMark added in v0.3.0

type RichTextMark struct {
	Type string `json:"type"`
}

RichTextMark represents text formatting (bold, italic, etc.)

type RichTextNode added in v0.3.0

type RichTextNode struct {
	NodeType string          `json:"nodeType"`
	Value    string          `json:"value"`
	Data     map[string]any  `json:"data"`
	Marks    []RichTextMark  `json:"marks"`
	Content  []*RichTextNode `json:"content"`
}

RichTextNode represents a node in a Contentful RichText document

func (*RichTextNode) MarshalJSON added in v0.3.0

func (n *RichTextNode) MarshalJSON() ([]byte, error)

type SourceLocale added in v0.3.0

type SourceLocale struct {
	Locale    Locale          // Contentful locale, e.g., "en-US"
	DeepLLang DeepLSourceLang // DeepL source language code, e.g., "EN"
}

SourceLocale pairs a Contentful locale with its corresponding DeepL source language.

type SpaceModel

type SpaceModel struct {
	SpaceID       string
	Environment   string
	Locales       []LocaleInfo
	DefaultLocale Locale
	ContentTypes  map[string]*contentful.ContentType
	Entries       map[string]Entity // ID -> Entity
	Assets        map[string]Entity // ID -> Entity
	LastUpdated   time.Time
}

SpaceModel represents the structure of a Contentful space

type TargetLocale added in v0.3.0

type TargetLocale struct {
	Locale    Locale          // Contentful locale, e.g., "de-DE"
	DeepLLang DeepLTargetLang // DeepL target language code, e.g., "DE"
}

TargetLocale pairs a Contentful locale with its corresponding DeepL target language.

type TranslateBatchFunc added in v0.3.0

type TranslateBatchFunc func(texts []string) (translated []string, billedCharacters int, err error)

TranslateBatchFunc is called with all text chunks at once for batch translation. This is more efficient when using APIs like DeepL that support batch requests. The returned slice must have the same length and order as the input slice. It also returns the total number of billed characters for the batch.

type TranslateFunc added in v0.3.0

type TranslateFunc func(text string) (translated string, billedCharacters int, err error)

TranslateFunc is called for each text chunk that needs translation. It receives the source text and should return the translated text along with the number of billed characters.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL