github.com/linchen2chris/hugo@v0.0.0-20230307053224-cec209389705/resources/page/pages_language_merge.go (about)

     1  // Copyright 2019 The Hugo Authors. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package page
    15  
    16  import (
    17  	"fmt"
    18  )
    19  
    20  var _ pagesLanguageMerger = (*Pages)(nil)
    21  
    22  type pagesLanguageMerger interface {
    23  	MergeByLanguage(other Pages) Pages
    24  	// Needed for integration with the tpl package.
    25  	MergeByLanguageInterface(other any) (any, error)
    26  }
    27  
    28  // MergeByLanguage supplies missing translations in p1 with values from p2.
    29  // The result is sorted by the default sort order for pages.
    30  func (p1 Pages) MergeByLanguage(p2 Pages) Pages {
    31  	merge := func(pages *Pages) {
    32  		m := make(map[string]bool)
    33  		for _, p := range *pages {
    34  			m[p.TranslationKey()] = true
    35  		}
    36  
    37  		for _, p := range p2 {
    38  			if _, found := m[p.TranslationKey()]; !found {
    39  				*pages = append(*pages, p)
    40  			}
    41  		}
    42  
    43  		SortByDefault(*pages)
    44  	}
    45  
    46  	out, _ := spc.getP("pages.MergeByLanguage", merge, p1, p2)
    47  
    48  	return out
    49  }
    50  
    51  // MergeByLanguageInterface is the generic version of MergeByLanguage. It
    52  // is here just so it can be called from the tpl package.
    53  func (p1 Pages) MergeByLanguageInterface(in any) (any, error) {
    54  	if in == nil {
    55  		return p1, nil
    56  	}
    57  	p2, ok := in.(Pages)
    58  	if !ok {
    59  		return nil, fmt.Errorf("%T cannot be merged by language", in)
    60  	}
    61  	return p1.MergeByLanguage(p2), nil
    62  }