Skip to content
This repository has been archived by the owner on Dec 18, 2020. It is now read-only.

Commit

Permalink
push: split push up into locale_file and push_source
Browse files Browse the repository at this point in the history
  • Loading branch information
sacry-dyn committed Nov 1, 2016
1 parent 7078f48 commit 4ef38b4
Show file tree
Hide file tree
Showing 4 changed files with 350 additions and 324 deletions.
46 changes: 46 additions & 0 deletions locale_file.go
@@ -0,0 +1,46 @@
package main

import (
"fmt"
"os"
"path/filepath"
"strings"
)

type LocaleFiles []*LocaleFile

type LocaleFile struct {
Path, Name, ID, Code, Tag, FileFormat string
ExistsRemote bool
}

func (localeFile *LocaleFile) RelPath() string {
callerPath, _ := os.Getwd()
relativePath, _ := filepath.Rel(callerPath, localeFile.Path)
return relativePath
}

// Locale to Path mapping
func (localeFile *LocaleFile) Message() string {
str := ""
if Debug {
if localeFile.Name != "" {
str = fmt.Sprintf("%s Name: %s", str, localeFile.Name)
}
if localeFile.ID != "" {
str = fmt.Sprintf("%s Id: %s", str, localeFile.ID)
}
if localeFile.Code != "" {
str = fmt.Sprintf("%s Code: %s", str, localeFile.Code)
}
if localeFile.Tag != "" {
str = fmt.Sprintf("%s Tag: %s", str, localeFile.Tag)
}
if localeFile.FileFormat != "" {
str = fmt.Sprintf("%s Format: %s", str, localeFile.FileFormat)
}
} else {
str = fmt.Sprintf("%s", localeFile.Name)
}
return strings.TrimSpace(str)
}
270 changes: 4 additions & 266 deletions push.go
Expand Up @@ -7,8 +7,6 @@ import (
"regexp"
"strings"

"gopkg.in/yaml.v2"

"unicode/utf8"

"github.com/phrase/phraseapp-go/phraseapp"
Expand All @@ -35,6 +33,10 @@ func (cmd *PushCommand) Run() error {
return err
}

if err := sources.Validate(); err != nil {
return err
}

formatMap, err := GetFormats(client)
if err != nil {
return fmt.Errorf("Error retrieving format list from PhraseApp: %s", err)
Expand Down Expand Up @@ -70,83 +72,7 @@ func (cmd *PushCommand) Run() error {
return nil
}

type Sources []*Source

func (sources Sources) ProjectIds() []string {
projectIds := []string{}
for _, source := range sources {
projectIds = append(projectIds, source.ProjectID)
}
return projectIds
}

type Source struct {
File string
ProjectID string
AccessToken string
FileFormat string
Params *phraseapp.UploadParams

RemoteLocales []*phraseapp.Locale
Format *phraseapp.Format
}

func (src *Source) UnmarshalYAML(unmarshal func(interface{}) error) error {
m := map[string]interface{}{}
err := phraseapp.ParseYAMLToMap(unmarshal, map[string]interface{}{
"file": &src.File,
"project_id": &src.ProjectID,
"access_token": &src.AccessToken,
"file_format": &src.FileFormat,
"params": &m,
})
if err != nil {
return err
}

src.Params = new(phraseapp.UploadParams)
return src.Params.ApplyValuesFromMap(m)
}

var separator = string(os.PathSeparator)

func (source *Source) CheckPreconditions() error {
if err := ValidPath(source.File, source.FileFormat, ""); err != nil {
return err
}

duplicatedPlaceholders := []string{}
for _, name := range []string{"<locale_name>", "<locale_code>", "<tag>"} {
if strings.Count(source.File, name) > 1 {
duplicatedPlaceholders = append(duplicatedPlaceholders, name)
}
}

starCount := strings.Count(source.File, "*")
recCount := strings.Count(source.File, "**")

// starCount contains the `**` so that must be taken into account.
if starCount-(recCount*2) > 1 {
duplicatedPlaceholders = append(duplicatedPlaceholders, "*")
}

if recCount > 1 {
duplicatedPlaceholders = append(duplicatedPlaceholders, "**")
}

if len(duplicatedPlaceholders) > 0 {
dups := strings.Join(duplicatedPlaceholders, ", ")
return fmt.Errorf(fmt.Sprintf("%s can only occur once in a file pattern!", dups))
}

return nil
}

func (source *Source) Push(client *phraseapp.Client) error {
if err := source.CheckPreconditions(); err != nil {
return err
}

localeFiles, err := source.LocaleFiles()
if err != nil {
return err
Expand Down Expand Up @@ -183,84 +109,6 @@ func (source *Source) Push(client *phraseapp.Client) error {
return nil
}

func (source *Source) createLocale(client *phraseapp.Client, localeFile *LocaleFile) (*phraseapp.LocaleDetails, error) {
localeDetails, err := source.localeShow(client, localeFile)
if err != nil && !strings.Contains(err.Error(), "404") {
return nil, err
}

if localeDetails != nil {
return localeDetails, nil
}

localeParams := new(phraseapp.LocaleParams)

if localeFile.Name != "" {
localeParams.Name = &localeFile.Name
} else if localeFile.Code != "" {
localeParams.Name = &localeFile.Code
}

if localeFile.Code == "" {
localeFile.Code = localeFile.Name
}

localeName := source.replacePlaceholderInParams(localeFile)
if localeName != "" && localeName != localeFile.Code {
localeParams.Name = &localeName
}

if localeFile.Code != "" {
localeParams.Code = &localeFile.Code
}

localeDetails, err = client.LocaleCreate(source.ProjectID, localeParams)
if err != nil {
return nil, err
}
return localeDetails, nil
}

func (source *Source) replacePlaceholderInParams(localeFile *LocaleFile) string {
if localeFile.Code != "" && strings.Contains(source.GetLocaleID(), "<locale_code>") {
return strings.Replace(source.GetLocaleID(), "<locale_code>", localeFile.Code, 1)
}
return ""
}

func (source *Source) uploadFile(client *phraseapp.Client, localeFile *LocaleFile) error {
if Debug {
fmt.Fprintln(os.Stdout, "Source file pattern:", source.File)
fmt.Fprintln(os.Stdout, "Actual file location:", localeFile.Path)
}

params := new(phraseapp.UploadParams)
*params = *source.Params

params.File = &localeFile.Path

if params.LocaleID == nil {
switch {
case localeFile.ID != "":
params.LocaleID = &localeFile.ID
case localeFile.Code != "":
params.LocaleID = &localeFile.Code
}
}

if localeFile.Tag != "" {
var v string
if params.Tags != nil {
v = *params.Tags + ","
}
v += localeFile.Tag
params.Tags = &v
}

_, err := client.UploadCreate(source.ProjectID, params)
return err
}

func (source *Source) SystemFiles() ([]string, error) {
pattern := placeholderRegexp.ReplaceAllString(source.File, "*")
parts := strings.SplitN(pattern, "**", 2)
Expand Down Expand Up @@ -317,14 +165,6 @@ func (source *Source) SystemFiles() ([]string, error) {
return matches, nil
}

func isDir(path string) bool {
stat, err := os.Lstat(path)
if err != nil {
return false
}
return stat.IsDir()
}

func validateFileCandidate(tokens []string, ignoreTokenCnt int, cand string) bool {
candTokens := splitPathIntoSegments(cand)
candTokenCnt := len(candTokens)
Expand Down Expand Up @@ -607,74 +447,6 @@ func extractParamFromPathToken(localeFile *LocaleFile, srcToken, pathToken strin
}
}

func SourcesFromConfig(cmd *PushCommand) (Sources, error) {
if cmd.Config.Sources == nil || len(cmd.Config.Sources) == 0 {
return nil, fmt.Errorf("no sources for upload specified")
}

tmp := struct {
Sources Sources
}{}
err := yaml.Unmarshal(cmd.Config.Sources, &tmp)
if err != nil {
return nil, err
}
srcs := tmp.Sources

token := cmd.Credentials.Token
projectId := cmd.Config.DefaultProjectID
fileFormat := cmd.Config.DefaultFileFormat

validSources := []*Source{}
for _, source := range srcs {
if source == nil {
continue
}
if source.ProjectID == "" {
source.ProjectID = projectId
}
if source.AccessToken == "" {
source.AccessToken = token
}
if source.Params == nil {
source.Params = new(phraseapp.UploadParams)
}

if source.Params.FileFormat == nil {
switch {
case source.FileFormat != "":
source.Params.FileFormat = &source.FileFormat
case fileFormat != "":
source.Params.FileFormat = &fileFormat
}
}
validSources = append(validSources, source)
}

if len(validSources) <= 0 {
return nil, fmt.Errorf("no sources could be identified! Refine the sources list in your config")
}

return validSources, nil
}

func (source *Source) GetLocaleID() string {
if source.Params != nil && source.Params.LocaleID != nil {
return *source.Params.LocaleID
}
return ""
}

func (source *Source) GetFileFormat() string {
if source.Params != nil && source.Params.FileFormat != nil {
return *source.Params.FileFormat
}
if source.FileFormat != "" {
return source.FileFormat
}
return ""
}

func (localeFile *LocaleFile) shouldCreateLocale(source *Source) bool {
if localeFile.ExistsRemote {
return false
Expand All @@ -690,37 +462,3 @@ func (localeFile *LocaleFile) shouldCreateLocale(source *Source) bool {
// every other source should be uploaded and validated in uploads#create
return (localeFile.Name != "" || localeFile.Code != "")
}

func (source *Source) localeShow(client *phraseapp.Client, localeFile *LocaleFile) (*phraseapp.LocaleDetails, error) {
identifier := localeFile.localeIdentifier(source)
if identifier == "" {
return nil, nil
}

localeDetail, err := client.LocaleShow(source.ProjectID, identifier)
if err != nil {
return nil, err
}
if localeDetail != nil {
return localeDetail, nil
}

return nil, nil
}

func (localeFile *LocaleFile) localeIdentifier(source *Source) string {
localeName := source.replacePlaceholderInParams(localeFile)
if localeName != "" && localeName != localeFile.Code {
return localeName
}

if localeFile.Name != "" {
return localeFile.Name
}

if localeFile.Code != "" {
return localeFile.Code
}

return ""
}

0 comments on commit 4ef38b4

Please sign in to comment.