Commits

David Keegan committed 3dfd03e

*merging 'genstrings' and 'Translate' into 'Localize'
*fixing bugs in Localize.py
*--nibs is now optional, and if not specified all the nibs of the 'from language' will be localized

  • Participants
  • Parent commits 2dd4777

Comments (0)

Files changed (2)

 if a checksum for the file does not exist or the check does not match
 a new localized nib is created.
 
-Based on Philippe Casgrain's technique for localizing nibs at build
+Based on Philippe Casgrain's 'Automatically localize your nibs when building'
     http://developer.casgrain.com/?p=94
+    
+And Wil Shipley's 'Pimp My Code, Part 17: Lost in Translations'
+    http://wilshipley.com/blog/2009/10/pimp-my-code-part-17-lost-in.html
 
 Written by David Keegan for Murky
     http://bitbucket.org/snej/murky
 
 import time
 import codecs
-import os, sys
+import os, sys, glob
 import subprocess
 from optparse import OptionParser
 try:
     #python2.5
     import simplejson as json
 
+class LocalizationError(Exception):
+    def __init__(self, value):
+        self.value = value
+    def __str__(self):
+        return str(self.value)
+
 def detectEncoding(filepath):
     '''
     Try to detect the file's encoding.
     Convert the .strings file from utf-16 to utf-8
     This will allow files diffs
     '''
-    tempStrings = stringFile+'temp'
-    stringsEncoding = detectEncoding(stringFile)
-    #if the file is not already utf-8 re-encode it
-    if stringsEncoding != 'utf_8_sig':
-        fromFile = codecs.open(stringFile, 'r', stringsEncoding)
-        toFile = codecs.open(tempStrings, 'w', 'utf_8')
-        for eachLine in fromFile:
-            toFile.write(eachLine)
-        
-        toFile.close()            
-        fromFile.close()
-        
-        os.remove(stringFile)
-        os.rename(tempStrings, stringFile)
+    if os.path.isfile(stringFile):
+        tempStrings = stringFile+'temp'
+        stringsEncoding = detectEncoding(stringFile)
+        #if the file is not already utf-8 re-encode it
+        if stringsEncoding != 'utf_8_sig':
+            fromFile = codecs.open(stringFile, 'r', stringsEncoding)
+            toFile = codecs.open(tempStrings, 'w', 'utf_8')
+            for eachLine in fromFile:
+                toFile.write(eachLine)
+            
+            toFile.close()            
+            fromFile.close()
+            
+            os.remove(stringFile)
+            os.rename(tempStrings, stringFile)
         
 def runCommand(command, args):
     '''Run shell commands'''
     proc = subprocess.Popen(commandAndArgs, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     stdout, stderr = proc.communicate()
     if stderr != '':
-        raise TestPyError(commandAndArgs, stderr)
+        raise LocalizationError(commandAndArgs, stderr)
     return stdout
  
 def md5(file):
 def nibToStringFileName(nibFile):
     return nibFile.rstrip('.xib')+'.strings'
     
-def generateStringsFile(nibFile, utf8=False):
+def ibtoolsGenerateStringsFile(nibFile, utf8=False):
     '''
     Generate a .strings file from a nib
     If utf8 is True the .strings files will be re-encoded as utf-8
     
     print '  ', nibFileStrings, 'updated'
     
-def writeNib(fromFile, toFile, utf8=False):
+def ibtoolsWriteNib(fromFile, toFile, utf8=False):
     '''convert one localized nib from one language to another'''
     toStrings = nibToStringFileName(toFile)
     runCommand('ibtool', '--strings-file %s --write %s %s' % (toStrings, toFile, fromFile))
         
         print '  ', localizableStrings, 'updated'
  
-def localizeNibs(fromLang, toLangs, nibs, utf8=False, ignore=False):
+def localizeNibs(fromLang, toLangs, nibs=None, utf8=False, ignore=False):
     '''Localize nibs from one language to others'''
     
     #get the data from the json file
         jsonData = {}
         
     fromLangLproj = langProjName(fromLang)
+        
+    #if nibs is none, get all the nibs in the from language project
+    if nibs == None:
+        nibs = []
+        for eachNib in glob.glob('%s/*.xib' % fromLangLproj):
+            nibs.append(eachNib.lstrip(fromLangLproj+'/').rstrip('.xib'))
+    
     for eachNib in nibs:
         eachNib = eachNib.strip()
         if not(eachNib.endswith('.xib')):
         fromNibMd5 = md5(fromNib)
         #check if the strings for the fromNib need to the updated
         if not(os.path.isfile(nibToStringFileName(fromNib))) or not(fromNib in jsonData) or jsonData[fromNib] != fromNibMd5:
-            generateStringsFile(fromNib, utf8)
+            ibtoolsGenerateStringsFile(fromNib, utf8)
         
         #write the localized nibs
         for eachToLang in toLangs:
             toLangLproj = langProjName(eachToLang)
             toNib =  os.path.join(toLangLproj, eachNib)
             if not(os.path.isfile(toNib)) or not(fromNib in jsonData) or jsonData[fromNib] != fromNibMd5:
-                writeNib(fromNib, toNib, utf8)
+                ibtoolsWriteNib(fromNib, toNib, utf8)
                 
         jsonData[fromNib] = fromNibMd5
                 
     startTime = time.time()
     
     opts = OptionParser()
-    opts.add_option('--from', '-f', dest='fromLang', help='the language to localize from', metavar='LANG')
-    opts.add_option('--to', '-t', dest='toLangs', help="an array of languages to localize to, separated by '|'", metavar='LANGS')
-    opts.add_option('--nibs', '-n', dest='nibs', help="an array of nibs to localize, separated by '|', .xib can be left off", metavar='NIBS')
-    opts.add_option('--utf8', '-u', dest='utf8', help='if this flag is present the .strings files will be re-encoded as utf-8', action="store_true", default=False)
-    opts.add_option('--ignore', '-i', dest='ignore', help='if this flag is present the md5 checksums will be ignored', action="store_true", default=False)
-    opts.add_option('--genstrings', '-g', dest='genstrings', help='if this argument is present the genstrings command line will be called', metavar='GLOB', default=None)
+    opts.add_option('--from', '-f', dest='fromLang', help='The language to localize from.', metavar='LANG')
+    opts.add_option('--to', '-t', dest='toLangs', help="An array of languages to localize to, separated by '|'.", metavar='LANGS')
+    opts.add_option('--nibs', '-n', dest='nibs', help="An array of nibs to localize, separated by '|', .xib can be left off. If this flag is left out all the nibs in the from language will be used.", metavar='NIBS')
+    opts.add_option('--utf8', '-u', dest='utf8', help='If this flag is present the .strings files will be re-encoded as utf-8.', action="store_true", default=False)
+    opts.add_option('--ignore', '-i', dest='ignore', help='If this flag is present the md5 checksums will be ignored.', action="store_true", default=False)
+    opts.add_option('--genstrings', '-g', dest='genstrings', help='File name or glob string. If this argument is present the genstrings command line will be called.', metavar='GLOB', default=None)
     options, arguments = opts.parse_args()
     
     if options.genstrings != None:  
         genStrings(options.toLangs.split('|'), options.genstrings, options.utf8)
         print 'Strings updated in %.2f seconds' % (time.time()-startTime)
-    else:      
-        localizeNibs(options.fromLang, options.toLangs.split('|'), options.nibs.split('|'), options.utf8, options.ignore)
+    else:
+        nibs = options.nibs
+        if nibs != None:
+            nibs = options.nibs.split('|')
+        localizeNibs(options.fromLang, options.toLangs.split('|'), nibs, options.utf8, options.ignore)
         print 'Nibs updated in %.2f seconds' % (time.time()-startTime)
     

File Murky.xcodeproj/project.pbxproj

 			buildPhases = (
 				8D11072C0486CEB800E47090 /* Sources */,
 				8D11072E0486CEB800E47090 /* Frameworks */,
-				27E396E710E87CAC009F99ED /* genstrings */,
-				37915E6310E900A00057D687 /* Translate */,
+				37915E6310E900A00057D687 /* Localize */,
 				8D1107290486CEB800E47090 /* Resources */,
 			);
 			buildRules = (
 /* End PBXResourcesBuildPhase section */
 
 /* Begin PBXShellScriptBuildPhase section */
-		27E396E710E87CAC009F99ED /* genstrings */ = {
-			isa = PBXShellScriptBuildPhase;
-			buildActionMask = 2147483647;
-			comments = "Taken from Wil Shipley's blog post:\nhttp://wilshipley.com/blog/2009/10/pimp-my-code-part-17-lost-in.html";
-			files = (
-			);
-			inputPaths = (
-			);
-			name = genstrings;
-			outputPaths = (
-			);
-			runOnlyForDeploymentPostprocessing = 0;
-			shellPath = /bin/zsh;
-			shellScript = "# -q silences duplicate comments with same key warning\n./Localize.py --to English --genstrings \"./**/*.[hm]\" --utf8";
-			showEnvVarsInLog = 0;
-		};
-		37915E6310E900A00057D687 /* Translate */ = {
+		37915E6310E900A00057D687 /* Localize */ = {
 			isa = PBXShellScriptBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
 			);
 			inputPaths = (
 			);
-			name = Translate;
+			name = Localize;
 			outputPaths = (
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 			shellPath = /bin/sh;
-			shellScript = "# Localize nibs\n./Localize.py --from English --to \"French|German\" --nibs \"MainMenu|Projects|Repo\" --utf8\n";
+			shellScript = "# -q silences duplicate comments with same key warning\n./Localize.py --to English --genstrings \"./**/*.[hm]\" --utf8\n\n# Localize nibs\n./Localize.py --from English --to \"French|German\" --utf8\n";
 		};
 /* End PBXShellScriptBuildPhase section */