Skip to content

Commit

Permalink
make additional message strings translatable
Browse files Browse the repository at this point in the history
Following on from the changes in PR git-lfs#4781, we can make
additional message strings translatable using the
tr.Tr.Get() method.

Because this method performs printf(3)-style format string
parsing and interpolation, we can simplify some of the
surrounding calls, e.g., from fmt.Errorf() to errors.New(),
and from fmt.Fprintf() to fmt.Fprintln().  This ensures
that if either the translated text or any interpolated
arguments happen to contain character sequences that would
be interpreted as Go format specifiers (e.g., "%s" or "%d"),
these will not result in warnings such as "%!s(MISSING)"
in the output text.

Note also that we try to remove newlines from the message
strings were possible and change the surrounding calls to
append them instead, e.g., with fmt.Fprintln().
  • Loading branch information
chrisd8088 committed Jan 30, 2022
1 parent e1f2b1f commit 04abbd8
Show file tree
Hide file tree
Showing 48 changed files with 197 additions and 176 deletions.
4 changes: 2 additions & 2 deletions commands/command_checkout.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func checkoutCommand(cmd *cobra.Command, args []string) {

if checkoutTo != "" && stage != git.IndexStageDefault {
if len(args) != 1 {
Exit("--to requires exactly one Git LFS object file path")
Exit(tr.Tr.Get("--to requires exactly one Git LFS object file path"))
}
checkoutConflict(rootedPaths(args)[0], stage)
return
Expand Down Expand Up @@ -155,7 +155,7 @@ func whichCheckout() (stage git.IndexStage, err error) {
func rootedPaths(args []string) []string {
pathConverter, err := lfs.NewCurrentToRepoPatternConverter(cfg)
if err != nil {
Panic(err, "Could not checkout")
Panic(err, tr.Tr.Get("Could not checkout"))
}

rootedpaths := make([]string, 0, len(args))
Expand Down
24 changes: 14 additions & 10 deletions commands/command_dedup.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func dedupTestCommand(*cobra.Command, []string) {

if supported, err := tools.CheckCloneFileSupported(cfg.TempDir()); err != nil || !supported {
if err == nil {
err = errors.New("Unknown reason")
err = errors.New(tr.Tr.Get("Unknown reason"))
}
Exit(tr.Tr.Get("This system does not support de-duplication: %s", err))
}
Expand All @@ -38,7 +38,7 @@ func dedupTestCommand(*cobra.Command, []string) {
Exit(tr.Tr.Get("This platform supports file de-duplication, however, Git LFS extensions are configured and therefore de-duplication can not be used."))
}

Print("OK: This platform and repository support file de-duplication.")
Print(tr.Tr.Get("OK: This platform and repository support file de-duplication."))
}

func dedupCommand(cmd *cobra.Command, args []string) {
Expand Down Expand Up @@ -79,7 +79,7 @@ func dedupCommand(cmd *cobra.Command, args []string) {
} else if !success {
Error(tr.Tr.Get("Skipped: %s (Size: %d)", p.Name, p.Size))
} else if success {
Print("Success: %s (Size: %d)", p.Name, p.Size)
Print(tr.Tr.Get("Success: %s (Size: %d)", p.Name, p.Size))

atomic.AddInt64(&dedupStats.totalProcessedCount, 1)
atomic.AddInt64(&dedupStats.totalProcessedSize, p.Size)
Expand All @@ -91,11 +91,15 @@ func dedupCommand(cmd *cobra.Command, args []string) {
ExitWithError(err)
}

Print("\n\nFinished successfully.\n"+
" De-duplicated size: %d bytes\n"+
" count: %d",
dedupStats.totalProcessedSize,
dedupStats.totalProcessedCount)
// TRANSLATORS: The second and third strings should have the colons
// aligned in a column.
Print("\n\n%s\n %s\n %s", tr.Tr.Get("Finished successfully."),
tr.Tr.GetN(
"De-duplicated size: %d byte",
"De-duplicated size: %d bytes",
int(dedupStats.totalProcessedSize),
dedupStats.totalProcessedSize),
tr.Tr.Get(" count: %d", dedupStats.totalProcessedCount))
}

// dedup executes
Expand All @@ -104,7 +108,7 @@ func dedup(p *lfs.WrappedPointer) (success bool, err error) {
// PRECONDITION, check ofs object exists or skip this file.
if !cfg.LFSObjectExists(p.Oid, p.Size) { // Not exists,
// Basically, this is not happens because executing 'git status' in `git.IsWorkingCopyDirty()` recover it.
return false, errors.New("Git LFS object file does not exist")
return false, errors.New(tr.Tr.Get("Git LFS object file does not exist"))
}

// DO de-dup
Expand All @@ -126,7 +130,7 @@ func dedup(p *lfs.WrappedPointer) (success bool, err error) {
if ok, err := tools.CloneFileByPath(dstFile, srcFile); err != nil {
return false, err
} else if !ok {
return false, errors.Errorf("unknown clone file error")
return false, errors.Errorf(tr.Tr.Get("unknown clone file error"))
}

// Recover original state
Expand Down
3 changes: 2 additions & 1 deletion commands/command_env.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/git-lfs/git-lfs/v3/config"
"github.com/git-lfs/git-lfs/v3/git"
"github.com/git-lfs/git-lfs/v3/lfs"
"github.com/git-lfs/git-lfs/v3/tr"
"github.com/spf13/cobra"
)

Expand All @@ -12,7 +13,7 @@ func envCommand(cmd *cobra.Command, args []string) {

gitV, err := git.Version()
if err != nil {
gitV = "Error getting Git version: " + err.Error()
gitV = tr.Tr.Get("Error getting Git version: %s", err.Error())
}

Print(config.VersionDesc)
Expand Down
2 changes: 1 addition & 1 deletion commands/command_fsck.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ func doFsckPointers(start, end string) []corruptPointer {
corruptPointers = append(corruptPointers, cp)
}
} else {
Panic(err, "Error checking Git LFS files")
Panic(err, tr.Tr.Get("Error checking Git LFS files"))
}
})

Expand Down
2 changes: 1 addition & 1 deletion commands/command_install.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func cmdInstallOptions() *lfs.FilterOptions {
// since we can't detect it correctly.
uid := os.Geteuid()
if systemInstall && uid != 0 && uid != -1 {
Print("warning: current user is not root/admin, system install is likely to fail.")
Print(tr.Tr.Get("warning: current user is not root/admin, system install is likely to fail."))
}

return &lfs.FilterOptions{
Expand Down
2 changes: 1 addition & 1 deletion commands/command_migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func migrate(args []string, r *githistory.Rewriter, l *tasklog.Logger, opts *git
func getObjectDatabase() (*gitobj.ObjectDatabase, error) {
dir, err := git.GitCommonDir()
if err != nil {
return nil, errors.Wrap(err, "cannot open root")
return nil, errors.Wrap(err, tr.Tr.Get("cannot open root"))
}

return git.ObjectDatabase(cfg.OSEnv(), cfg.GitEnv(), dir, cfg.TempDir())
Expand Down
4 changes: 2 additions & 2 deletions commands/command_track.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,13 @@ ArgsLoop:
attribContents, err = ioutil.ReadFile(".gitattributes")
// it's fine for file to not exist
if err != nil && !os.IsNotExist(err) {
Print("Error reading '.gitattributes' file")
Print(tr.Tr.Get("Error reading '.gitattributes' file"))
return
}
// Re-generate the file with merge of old contents and new (to deal with changes)
attributesFile, err = os.OpenFile(".gitattributes", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0660)
if err != nil {
Print("Error opening '.gitattributes' file")
Print(tr.Tr.Get("Error opening '.gitattributes' file"))
return
}
defer attributesFile.Close()
Expand Down
2 changes: 1 addition & 1 deletion commands/command_unlock.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func unlockCommand(cmd *cobra.Command, args []string) {
}

if !locksCmdFlags.JSON {
Print("Unlocked %s", path)
Print(tr.Tr.Get("Unlocked %s", path))
continue
}
locks = append(locks, unlockResponse{
Expand Down
2 changes: 1 addition & 1 deletion commands/command_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func updateCommand(cmd *cobra.Command, args []string) {
}

if updateForce && updateManual {
Exit("You cannot use --force and --manual options together")
Exit(tr.Tr.Get("You cannot use --force and --manual options together"))
}

if updateManual {
Expand Down
51 changes: 26 additions & 25 deletions commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/git-lfs/git-lfs/v3/subprocess"
"github.com/git-lfs/git-lfs/v3/tools"
"github.com/git-lfs/git-lfs/v3/tq"
"github.com/git-lfs/git-lfs/v3/tr"
)

// Populate man pages
Expand Down Expand Up @@ -99,7 +100,7 @@ func newLockClient() *locking.Client {
}

if err != nil {
Exit("Unable to create lock system: %v", err.Error())
Exit(tr.Tr.Get("Unable to create lock system: %v", err.Error()))
}

// Configure dirs
Expand Down Expand Up @@ -151,9 +152,9 @@ func getHookInstallSteps() string {
hooks := lfs.LoadHooks(hookDir, cfg)
steps := make([]string, 0, len(hooks))
for _, h := range hooks {
steps = append(steps, fmt.Sprintf(
"Add the following to '.git/hooks/%s':\n\n%s",
h.Type, tools.Indent(h.Contents)))
steps = append(steps, fmt.Sprintf("%s\n\n%s",
tr.Tr.Get("Add the following to '.git/hooks/%s':", h.Type),
tools.Indent(h.Contents)))
}

return strings.Join(steps, "\n\n")
Expand All @@ -177,7 +178,7 @@ func installHooks(force bool) error {
// uninstallHooks removes all hooks in range of the `hooks` var.
func uninstallHooks() error {
if !cfg.InRepo() {
return errors.New("Not in a Git repository")
return errors.New(tr.Tr.Get("Not in a git repository"))
}

hookDir, err := cfg.HookDir()
Expand Down Expand Up @@ -263,7 +264,7 @@ func LoggedError(err error, format string, args ...interface{}) {
file := handlePanic(err)

if len(file) > 0 {
fmt.Fprintf(os.Stderr, "\nErrors logged to '%s'.\nUse `git lfs logs last` to view the log.\n", file)
fmt.Fprintf(os.Stderr, "\n%s\n", tr.Tr.Get("Errors logged to '%s'.\nUse `git lfs logs last` to view the log.", file))
}
}

Expand All @@ -276,7 +277,7 @@ func Panic(err error, format string, args ...interface{}) {

func Cleanup() {
if err := cfg.Cleanup(); err != nil {
fmt.Fprintf(os.Stderr, "Error clearing old temporary files: %s\n", err)
fmt.Fprintln(os.Stderr, tr.Tr.Get("Error clearing old temporary files: %s", err))
}
}

Expand All @@ -297,9 +298,9 @@ func requireStdin(msg string) {

stat, err := os.Stdin.Stat()
if err != nil {
out = fmt.Sprintf("Cannot read from STDIN: %s (%s)", msg, err)
out = tr.Tr.Get("Cannot read from STDIN: %s (%s)", msg, err)
} else if (stat.Mode() & os.ModeCharDevice) != 0 {
out = fmt.Sprintf("Cannot read from STDIN: %s", msg)
out = tr.Tr.Get("Cannot read from STDIN: %s", msg)
}

if len(out) > 0 {
Expand All @@ -310,7 +311,7 @@ func requireStdin(msg string) {

func requireInRepo() {
if !cfg.InRepo() {
Print("Not in a Git repository.")
Print(tr.Tr.Get("Not in a Git repository."))
os.Exit(128)
}
}
Expand All @@ -320,7 +321,7 @@ func requireInRepo() {
// be determined), this function will terminate the program.
func requireWorkingCopy() {
if cfg.LocalWorkingDir() == "" {
Print("This operation must be run in a work tree.")
Print(tr.Tr.Get("This operation must be run in a work tree."))
os.Exit(128)
}
}
Expand All @@ -330,7 +331,7 @@ func setupRepository() {
bare, err := git.IsBare()
if err != nil {
ExitWithError(errors.Wrap(
err, "Could not determine bareness"))
err, tr.Tr.Get("Could not determine bareness")))
}
verifyRepositoryVersion()

Expand All @@ -345,7 +346,7 @@ func verifyRepositoryVersion() {
if val == "" {
cfg.SetGitLocalKey(key, "0")
} else if val != "0" {
Print("Unknown repository format version: %s", val)
Print(tr.Tr.Get("Unknown repository format version: %s", val))
os.Exit(128)
}
}
Expand All @@ -362,12 +363,12 @@ func changeToWorkingCopy() {
cwd, err := tools.Getwd()
if err != nil {
ExitWithError(errors.Wrap(
err, "Could not determine current working directory"))
err, tr.Tr.Get("Could not determine current working directory")))
}
cwd, err = tools.CanonicalizeSystemPath(cwd)
if err != nil {
ExitWithError(errors.Wrap(
err, "Could not canonicalize current working directory"))
err, tr.Tr.Get("Could not canonicalize current working directory")))
}

// If the current working directory is not within the repository's
Expand Down Expand Up @@ -416,12 +417,12 @@ func logPanic(loggedError error) string {

if err := tools.MkdirAll(cfg.LocalLogDir(), cfg); err != nil {
full = ""
fmt.Fprintf(fmtWriter, "Unable to log panic to '%s': %s\n\n", cfg.LocalLogDir(), err.Error())
fmt.Fprintf(fmtWriter, "%s\n\n", tr.Tr.Get("Unable to log panic to '%s': %s", cfg.LocalLogDir(), err.Error()))
} else if file, err := os.Create(full); err != nil {
filename := full
full = ""
defer func() {
fmt.Fprintf(fmtWriter, "Unable to log panic to '%s'\n\n", filename)
fmt.Fprintf(fmtWriter, "%s\n\n", tr.Tr.Get("Unable to log panic to '%s'", filename))
logPanicToWriter(fmtWriter, err, lineEnding)
}()
} else {
Expand All @@ -439,7 +440,7 @@ func ipAddresses() []string {
ips := make([]string, 0, 1)
ifaces, err := net.Interfaces()
if err != nil {
ips = append(ips, "Error getting network interface: "+err.Error())
ips = append(ips, tr.Tr.Get("Error getting network interface: %s", err.Error()))
return ips
}
for _, i := range ifaces {
Expand All @@ -452,7 +453,7 @@ func ipAddresses() []string {
addrs, _ := i.Addrs()
l := make([]string, 0, 1)
if err != nil {
ips = append(ips, "Error getting IP address: "+err.Error())
ips = append(ips, tr.Tr.Get("Error getting IP address: %s", err.Error()))
continue
}
for _, addr := range addrs {
Expand All @@ -479,7 +480,7 @@ func logPanicToWriter(w io.Writer, loggedError error, le string) {
// log the version
gitV, err := git.Version()
if err != nil {
gitV = "Error getting Git version: " + err.Error()
gitV = tr.Tr.Get("Error getting Git version: %s", err.Error())
}

fmt.Fprint(w, config.VersionDesc, le)
Expand All @@ -503,17 +504,17 @@ func logPanicToWriter(w io.Writer, loggedError error, le string) {
fmt.Fprintf(w, "%s=%v%s", key, val, le)
}

fmt.Fprint(w, le, "Current time in UTC:", le)
fmt.Fprint(w, le, tr.Tr.Get("Current time in UTC:"), le)
fmt.Fprint(w, time.Now().UTC().Format("2006-01-02 15:04:05"), le)

fmt.Fprint(w, le, "Environment:", le)
fmt.Fprint(w, le, tr.Tr.Get("Environment:"), le)

// log the environment
for _, env := range lfs.Environ(cfg, getTransferManifest(), oldEnv) {
fmt.Fprint(w, env, le)
}

fmt.Fprint(w, le, "Client IP addresses:", le)
fmt.Fprint(w, le, tr.Tr.Get("Client IP addresses:"), le)

for _, ip := range ipAddresses() {
fmt.Fprint(w, ip, le)
Expand Down Expand Up @@ -556,8 +557,8 @@ func requireGitVersion() {
if !git.IsGitVersionAtLeast(minimumGit) {
gitver, err := git.Version()
if err != nil {
Exit("Error getting Git version: %s", err)
Exit(tr.Tr.Get("Error getting Git version: %s", err))
}
Exit("Git version %s or higher is required for Git LFS; your version: %s", minimumGit, gitver)
Exit(tr.Tr.Get("Git version %s or higher is required for Git LFS; your version: %s", minimumGit, gitver))
}
}
2 changes: 1 addition & 1 deletion commands/lockverifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ type lockVerifier struct {

func (lv *lockVerifier) Verify(ref *git.Ref) {
if ref == nil {
panic("no ref specified for verification")
panic(tr.Tr.Get("no ref specified for verification"))
}

if lv.verifyState == verifyStateDisabled || lv.verifiedRefs[ref.Refspec()] {
Expand Down
2 changes: 1 addition & 1 deletion commands/uploader.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func uploadForRefUpdates(ctx *uploadContext, updates []*git.RefUpdate, pushAll b
ctx.CollectErrors(q)

if err != nil {
return errors.Wrap(err, fmt.Sprintf("ref %q:", update.Left().Name))
return errors.Wrap(err, tr.Tr.Get("ref %q:", update.Left().Name))
}
}

Expand Down
4 changes: 2 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ func NewFrom(v Values) *Configuration {
// This branch should only ever trigger in
// tests, and only if they'd be broken.
if !isCaseSensitive && hasUpper {
panic(fmt.Sprintf("key %q has uppercase, shouldn't", key))
panic(tr.Tr.Get("key %q has uppercase, shouldn't", key))
}
for _, value := range values {
fmt.Printf("Config: %s=%s\n", key, value)
Expand Down Expand Up @@ -378,7 +378,7 @@ func (c *Configuration) loadGitDirs() {
errMsg := err.Error()
tracerx.Printf("Error running 'git rev-parse': %s", errMsg)
if errors.ExitStatus(err) != 128 {
fmt.Fprintf(os.Stderr, "Error: %s\n", errMsg)
fmt.Fprintln(os.Stderr, tr.Tr.Get("Error: %s", errMsg))
}
c.gitDir = &gitdir
}
Expand Down
Loading

0 comments on commit 04abbd8

Please sign in to comment.