github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/Unknwon/i18n/ui18n/sync.go (about)

     1  // Copyright 2013 Unknwon
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"): you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    11  // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    12  // License for the specific language governing permissions and limitations
    13  // under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"log"
    19  	"os"
    20  
    21  	ini "github.com/vodka-contrib/i18n/libraries/ini.v1"
    22  
    23  	"github.com/Unknwon/com"
    24  )
    25  
    26  var cmdSync = &Command{
    27  	UsageLine: "sync [source file] [target files]",
    28  	Short:     "sync keys for locale files",
    29  	Long: `to quickly sync keys for one or more locale files
    30  based on the one you already have
    31  `,
    32  }
    33  
    34  func init() {
    35  	cmdSync.Run = syncLocales
    36  }
    37  
    38  func syncLocales(cmd *Command, args []string) {
    39  	switch len(args) {
    40  	case 0:
    41  		log.Fatalln("No source locale file is specified")
    42  	case 1:
    43  		log.Fatalln("No target locale file is specified")
    44  	}
    45  
    46  	srcLocale, err := ini.Load(args[0])
    47  	if err != nil {
    48  		log.Fatalln(err)
    49  	}
    50  
    51  	// Load or create target locales.
    52  	targets := args[1:]
    53  	targetLocales := make([]*ini.File, len(targets))
    54  	for i, target := range targets {
    55  		if !com.IsExist(target) {
    56  			os.Create(target)
    57  		}
    58  
    59  		targetLocales[i], err = ini.Load(target)
    60  		if err != nil {
    61  			log.Fatalln(err)
    62  		}
    63  	}
    64  
    65  	for _, secName := range srcLocale.SectionStrings() {
    66  		keyList := srcLocale.Section(secName).KeyStrings()
    67  		for _, target := range targetLocales {
    68  			sec, err := target.GetSection(secName)
    69  			if err != nil {
    70  				if sec, err = target.NewSection(secName); err != nil {
    71  					log.Fatalln(err)
    72  				}
    73  			}
    74  			for _, k := range keyList {
    75  				if _, err = sec.GetKey(k); err != nil {
    76  					sec.NewKey(k, "")
    77  				}
    78  			}
    79  		}
    80  	}
    81  
    82  	for i, target := range targetLocales {
    83  		if err = target.SaveTo(targets[i]); err != nil {
    84  			log.Fatalln(err)
    85  		}
    86  	}
    87  }