def GetAppInfo(self, user_info): """Grabs the application info from the user_info dictionary. Args: user_info: dictionary of application info Returns: tuple of bundle_id, app_version, app_path """ bundle_id, app_version, app_path = None, None, None try: bundle_id = user_info['NSApplicationBundleIdentifier'] except KeyError: # Malformed applications may not have NSApplicationBundleIdentifier # Return NSApplicationName instead logging.error('Error reading bundle identifier: %s', user_info) bundle_id = user_info['NSApplicationName'] try: app_path = user_info['NSApplicationPath'] except KeyError: # Malformed applications may not have NSApplicationPath logging.error('Error reading application path: %s', user_info) if app_path: try: app_info_plist = NSDictionary.dictionaryWithContentsOfFile_( '%s/Contents/Info.plist' % app_path) if app_info_plist: app_version = app_info_plist['CFBundleVersion'] except KeyError: logging.error('Error reading application version from %s', app_path) return bundle_id, app_version, app_path
def rename_project(project_dir, new_project_name, bundle_id): search_string = "find %s -name *.xcodeproj" % project_dir name_to_change = os.popen(search_string).readlines()[0].rstrip().split("/")[-1].split(".")[0] project_directories = os.walk( project_dir ) # [y for x in os.walk(project_dir) for y in glob(os.path.join(x[0], ''))] for directory in project_directories: if "git" in directory[0]: continue expression = re.compile(re.escape(name_to_change), re.IGNORECASE) new_directory = expression.sub(new_project_name, directory[0]) print "creating %s" % new_directory os.makedirs(new_directory) files = [os.path.join(directory[0], x) for x in directory[2]] for dir_file in files: new_filename = expression.sub(new_project_name, dir_file) shutil.copyfile(dir_file, new_filename) replace_all(new_filename, name_to_change, new_project_name) plist_files = os.popen("find %s -name *Info.plist" % project_dir) for plist_file in plist_files: plist_file = plist_file.rstrip() plist = NSDictionary.dictionaryWithContentsOfFile_(plist_file) plist["CFBundleIdentifier"] = bundle_id plist.writeToFile_atomically_(plist_file, True)
def read_aae_file(path): plist = NSDictionary.dictionaryWithContentsOfFile_(path) if plist["adjustmentFormatIdentifier"] != "com.apple.photo": print "-- bad format identifier:", plist["adjustmentFormatIdentifier"] return None, None data = plist["adjustmentData"] d = ipaPASS.archiveFromData_error_(data, None) adjustments = d["adjustments"] orientation = d["metadata"]["orientation"] effect_names = [ d_["settings"]["effectName"] for d_ in d["adjustments"] if d_["identifier"] == "Effect"] if len(effect_names) == 0: print "-- no effect name" return None, None filter_name = "CIPhotoEffect" + effect_names[0] print "-- filter:", filter_name return filter_name, orientation
def __init__(self): """Create a new Preferences object from the current settings. Examples: >>> preferences = Preferences() >>> keys = ['latexViewer', 'latexEngine', 'latexUselatexmk', ... 'latexVerbose', 'latexDebug', 'latexAutoView', ... 'latexKeepLogWin', 'latexEngineOptions'] >>> all([key in preferences.prefs for key in keys]) True """ tm_preference_file = ('{}.plist'.format(environ['TM_APP_IDENTIFIER']) if 'TM_APP_IDENTIFIER' in environ else 'com.macromates.textmate.plist') self.default_values = { 'latexAutoView': 1, 'latexEngine': "pdflatex", 'latexEngineOptions': "", 'latexVerbose': 0, 'latexUselatexmk': 0, 'latexViewer': "TextMate", 'latexKeepLogWin': 1, 'latexDebug': 0, } self.prefs = self.default_values.copy() tm_prefs = NSDictionary.dictionaryWithContentsOfFile_( "{}/Library/Preferences/{}".format(environ["HOME"], tm_preference_file)) # Only save the values we really need for key in self.prefs: if key in tm_prefs: self.prefs[key] = tm_prefs[key]
def main(): parser = build_parser() options, args = parser.parse_args() if not args: parser.print_help() return if len(args) != 2: parser.error("Must specify both a source and destination") return if options.verbose: hdlr = logging.StreamHandler() fmt = logging.Formatter('%(message)s') hdlr.setFormatter(fmt) logger = logging.getLogger() logger.addHandler(hdlr) logger.setLevel(logging.INFO) else: logging.basicConfig() source, dest = map(os.path.normpath, args) if source == dest: parser.error("Source and destination may not be the same.") return if os.path.exists(dest): if options.killDest: deletePath(dest) else: parser.error("Destination already exists. -k to destroy or use different destination.") return if options.templateFile and (not os.path.exists(options.templateFile)): parser.error("Template file specified, but does not exist.") return info("Copying from '%s' to '%s'....", source, dest) shutil.copytree(source, dest) simplePathWalker(dest, killNasties, options) simplePathWalker(dest, doSubstitutions, options) if options.templateFile: options.template = NSDictionary.dictionaryWithContentsOfFile_(options.templateFile) if not options.template: parser.error("Failed to read template: %s" % options.templateFile) sys.exit(1) filesToRename = options.template['FilesToRename'] for k in filesToRename: leftPath = os.path.join(dest, k) rightPath = os.path.join(dest, filesToRename[k]) if not options.doReverse: info("rename %s ==> %s", rightPath, leftPath) os.rename(rightPath, leftPath) else: info("rename %s ==> %s", leftPath, rightPath) os.rename(leftPath, rightPath)
def load_puzzles(): if len(sys.argv) == 1: puzzles = load_puzzles_from_ipa() if not puzzles: print "Couldn't find the Lights Off app in your iTunes library. Please specify a valid puzzles.plist file path." sys.exit(1) return puzzles if not os.path.isfile(sys.argv[1]): print "Please specify a valid puzzles.plist file path." sys.exit(1) return NSDictionary.dictionaryWithContentsOfFile_(sys.argv[1])['puzzles']
def load_puzzles_from_ipa(): for ipa in glob("/Users/*/Music/iTunes/iTunes*/Mobile Applications/Lights Off*ipa"): try: z = ZipFile(open(ipa, "r")) with NamedTemporaryFile() as f: f.write(z.read('Payload/Lights Off.app/puzzles.plist')) f.flush() print f.name return NSDictionary.dictionaryWithContentsOfFile_(f.name)['puzzles'] except: continue return None
def GetPlist(plist): """Returns a dictionary from a given plist. Args: plist: plist to operate on Returns: Contents of the plist as a dict-like object. Raises: MissingImportsError: if NSDictionary is missing """ if NSDictionary: return NSDictionary.dictionaryWithContentsOfFile_(plist) else: raise MissingImportsError('NSDictionary not imported successfully.')
def notdefLayer( self ): try: from Foundation import NSBundle, NSClassFromString, NSDictionary bundle = NSBundle.bundleForClass_(NSClassFromString("GSExportInstanceOperation")) if bundle: path = bundle.pathForResource_ofType_("notDef","plist") layerDict = NSDictionary.dictionaryWithContentsOfFile_(path) layer = GSLayer.alloc().initWithDict_format_(layerDict,1) return layer return None except Exception as e: import traceback print(traceback.format_exc()) self.logToConsole( "notdefLayer: %s" % str(e) ) return None
def _extractClassesFromNibFromPath(self, path): path = os.path.normpath(path) if self.parsedNibs.has_key(path): return # we've already parsed this nib nibName = os.path.basename(path) nibInfo = NSDictionary.dictionaryWithContentsOfFile_( os.path.join(path, 'classes.nib')) if nibInfo is None: raise NibLoaderError("Invalid NIB file [%s]" % path) if not nibInfo.has_key('IBVersion'): raise NibLoaderError("Invalid NIB info") if nibInfo['IBVersion'] != '1': raise NibLoaderError("Unsupported NIB version") for rawClsInfo in nibInfo['IBClasses']: self._addClass(nibName, rawClsInfo) self.parsedNibs[path] = 1
def build_settings_dict(pbxfile, shared_scheme, build_action, configuration): action_scheme_dict = {'build' : 'BuildAction', 'test' : 'TestAction', 'archive' : 'ArchiveAction'} scheme_dir = "%s/xcshareddata/xcschemes/%s.xcscheme" % (os.path.dirname(os.path.realpath(pbxfile)), shared_scheme) scheme_xml = ET.parse(scheme_dir) action_node = scheme_xml.getiterator(action_scheme_dict[build_action])[0] buildable_node = action_node.getiterator("BuildableReference")[0] target_hash = buildable_node.get("BlueprintIdentifier") product_name = buildable_node.get("BlueprintName") pbxproj_plist = NSDictionary.dictionaryWithContentsOfFile_(pbxfile)['objects'] build_conf_for_target = pbxproj_plist[target_hash]['buildConfigurationList'] build_conf_list = pbxproj_plist[build_conf_for_target]['buildConfigurations'] build_conf_dict_for_target = [pbxproj_plist[build_conf] for build_conf in build_conf_list if pbxproj_plist[build_conf]['name'] == configuration][0] conf_atom = build_conf_dict_for_target['buildSettings'] atom = PBXAtom(conf_atom) return atom, product_name
def read_plist(plist): # 此处plist文件格式非标准,plist库无法解析,即使我去除所有的注释,仍然没用 # 所以调用objc的解析的方法 return NSDictionary.dictionaryWithContentsOfFile_(plist)
def init_with_files(fmeta, fdata): meta = NSDictionary.dictionaryWithContentsOfFile_(fmeta) data = NSArray.arrayWithContentsOfFile_(fdata) return meta, data
def readDictionary(filepath): """ Use Foundation calls to read a property list (dictionary) from disk. """ return NSDictionary.dictionaryWithContentsOfFile_(filepath)
def _readlib(path): return NSDictionary.dictionaryWithContentsOfFile_(path)
def copyFile(thePath): theSourcePath = os.path.join(theLibraryPath, thePath) theDestinationPath = os.path.join(thePhonePath, thePath) theDestinationDirectory = os.path.split(theDestinationPath)[0] if not os.path.exists(theDestinationDirectory): os.makedirs(theDestinationDirectory) if not os.path.exists(theDestinationPath): shutil.copyfile(theSourcePath, theDestinationPath) ######################################################################## try: from Foundation import (NSDictionary) d = NSDictionary.dictionaryWithContentsOfFile_(theLibraryFile) except: d = plistlib.readPlist(theLibraryFile) theTracks = d['Tracks'] ######################################################################## libraryPaths = [] phonePaths = [] addingPaths = [] removingPaths = [] validKinds = ['Matched AAC audio file', 'Purchased AAC audio file', 'AAC audio file', 'MPEG audio file'] count = 0 for theKey in theTracks: theTrack = theTracks[theKey]