def isServiceDisabled(source, service): """ Returns whether or not a service is disabled @param source: System root to examine @param service: launchd key representing service @return: True if service is disabled, False if enabled """ overridesPath = os.path.join(source, LAUNCHD_OVERRIDES) if os.path.isfile(overridesPath): overrides = readPlist(overridesPath) try: return overrides[service]['Disabled'] except KeyError: # Key is not in the overrides.plist, continue on pass prefsPath = os.path.join(source, LAUNCHD_PREFS_DIR, "%s.plist" % service) if os.path.isfile(prefsPath): prefs = readPlist(prefsPath) try: return prefs['Disabled'] except KeyError: return False raise ServiceStateError("Neither %s nor %s exist" % (overridesPath, prefsPath))
def main(): outset_plist = os.path.expanduser('~/Library/Preferences/com.github.outset.once.plist') outset_runonce_dir = '/usr/local/outset/login-once' try: scriptrunner = plistlib.readPlist(scriptrunner_plist) except IOError: # There isn't a scriptrunner plsit, no point carrying on sys.exit(0) try: d = plistlib.readPlist(outset_plist) except IOError: d = {} for script, date in scriptrunner.iteritems(): extension = get_script_type(os.path.join(scriptrunner_runonce_dir,script)) if script[-3:] != extension: script = script + extension outset_path = os.path.join(outset_runonce_dir, script) d[outset_path] = date plistlib.writePlist(d, outset_plist)
def getAppFilePath(self, file_path): # the reason we don't just do "open file.app" is because OS X has restrictions on open that make it hard to trace open = "/usr/bin/open" #find Info.plist plist = "" path = self.findFile(file_path, "Info.plist") for root, dirs, files in os.walk(file_path): for f in files: if f == "Info.plist": #read the plist file plist = plistlib.readPlist(os.path.join(root, f)) break if path == "": #no Info.plist found, this is an illegally structured app log.info("No Info.plist found within .app file") return (open, file_path) else: plist = plistlib.readPlist(path) try: #get the name of the main executable of this app exec_file = plist["CFBundleExecutable"] except KeyError: #no executable was listed, this is an illegally structured app log.info("No main executable name found in Info.plist") return (open, file_path) #get the full path of the executable exec_path = self.findFile(file_path, exec_file) return (exec_path, "")
def OpenPlistProject(self, filename): import invesalius.data.measures as ms import invesalius.data.mask as msk import invesalius.data.surface as srf if not const.VTK_WARNING: log_path = os.path.join(const.LOG_FOLDER, 'vtkoutput.txt') fow = vtk.vtkFileOutputWindow() fow.SetFileName(log_path) ow = vtk.vtkOutputWindow() ow.SetInstance(fow) filelist = Extract(filename, tempfile.mkdtemp()) dirpath = os.path.abspath(os.path.split(filelist[0])[0]) # Opening the main file from invesalius 3 project main_plist = os.path.join(dirpath ,'main.plist') project = plistlib.readPlist(main_plist) # case info self.name = project["name"] self.modality = project["modality"] self.original_orientation = project["orientation"] self.window = project["window_width"] self.level = project["window_level"] self.threshold_range = project["scalar_range"] self.spacing = project["spacing"] # Opening the matrix containing the slices filepath = os.path.join(dirpath, project["matrix"]["filename"]) self.matrix_filename = filepath self.matrix_shape = project["matrix"]['shape'] self.matrix_dtype = project["matrix"]['dtype'] # Opening the masks self.mask_dict = {} for index in project["masks"]: filename = project["masks"][index] filepath = os.path.join(dirpath, filename) m = msk.Mask() m.OpenPList(filepath) self.mask_dict[m.index] = m # Opening the surfaces self.surface_dict = {} for index in project["surfaces"]: filename = project["surfaces"][index] filepath = os.path.join(dirpath, filename) s = srf.Surface(int(index)) s.OpenPList(filepath) self.surface_dict[s.index] = s # Opening the measurements self.measurement_dict = {} measurements = plistlib.readPlist(os.path.join(dirpath, project["measurements"])) for index in measurements: measure = ms.Measurement() measure.Load(measurements[index]) self.measurement_dict[int(index)] = measure
def __init__(self, projectPath, unityProjectPath, plugins, testing = False): self.log("-------- Update Xcode Project --------") projectFile = projectPath + '/Unity-iPhone.xcodeproj/project.pbxproj' projectPlistPath = projectPath + '/Info.plist' self.infoPlist = plistlib.readPlist(projectPlistPath) self.p = XcodeProject.Load(projectFile) if unityProjectPath != None: additionsFilePath = unityProjectPath + '/Assets/Editor/Prime31/plistAdditions.plist' if os.path.isfile(additionsFilePath): additionsPlist = plistlib.readPlist(additionsFilePath) for k in additionsPlist: if k != 'plistKeys': self.infoPlist[k] = additionsPlist[k] for pluginName in plugins if type(plugins) == type([]) else [plugins]: self.run(pluginName, unityProjectPath + '/Assets/Editor/' + pluginName + '/') else: for pluginPath in plugins if type(plugins) == type([]) else [plugins]: if pluginPath[-1] == '/': pluginPath = pluginPath[:-1] pluginName = os.path.basename(pluginPath) self.run(pluginName, pluginPath + '/') plistlib.writePlist(self.infoPlist, projectPlistPath) self.p.save()
def parse_plist(self, preferences_file): """Try to reset preferences from preference_file.""" preferences_file = os.path.expanduser(preferences_file) # Try to open using FoundationPlist. If it's not available, # fall back to plistlib and hope it's not binary encoded. try: prefs = FoundationPlist.readPlist(preferences_file) except NameError: try: prefs = plistlib.readPlist(preferences_file) except ExpatError: # If we're on OSX, try to convert using another # tool. if is_osx(): subprocess.call(["plutil", "-convert", "xml1", preferences_file]) prefs = plistlib.readPlist(preferences_file) self.preferences_file = preferences_file self.user = prefs.get("jss_user") self.password = prefs.get("jss_pass") self.url = prefs.get("jss_url") if not all([self.user, self.password, self.url]): raise JSSPrefsMissingKeyError("Please provide all required " "preferences!") # Optional file repository array. Defaults to empty list. self.repos = [] for repo in prefs.get("repos", []): self.repos.append(dict(repo)) self.verify = prefs.get("verify", True) self.suppress_warnings = prefs.get("suppress_warnings", True)
def __init__(self, projectPath, unityProjectPath, plugins, testing = False): self.log("-------- Update Xcode Project --------") projectFile = projectPath + '/Unity-iPhone.xcodeproj/project.pbxproj' projectPlistPath = projectPath + '/Info.plist' self.infoPlist = plistlib.readPlist(projectPlistPath) self.p = XcodeProject.Load(projectFile) additionsFilePath = unityProjectPath + '/Assets/Editor/Gamedonia/plistAdditions.plist' if os.path.isfile(additionsFilePath): additionsPlist = plistlib.readPlist(additionsFilePath) for k in additionsPlist: if k != 'plistKeys': self.infoPlist[k] = additionsPlist[k] #Listamos las carpetas #plugins = get_immediate_subdirectories(unityProjectPath + '/Assets/Editor/') #self.log(plugins.count()) for pluginName in plugins if type(plugins) == type([]) else [plugins]: if pluginName != 'Gamedonia': self.run(pluginName, unityProjectPath + '/Assets/Editor/' + pluginName + '/') plistlib.writePlist(self.infoPlist, projectPlistPath) self.p.save()
def test_io_deprecated(self): pl_in = {"key": 42, "sub": {"key": 9, "alt": "value", "data": b"buffer"}} pl_out = plistlib._InternalDict( {"key": 42, "sub": plistlib._InternalDict({"key": 9, "alt": "value", "data": plistlib.Data(b"buffer")})} ) self.addCleanup(support.unlink, support.TESTFN) with self.assertWarns(DeprecationWarning): plistlib.writePlist(pl_in, support.TESTFN) with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlist(support.TESTFN) self.assertEqual(pl_out, pl2) os.unlink(support.TESTFN) with open(support.TESTFN, "wb") as fp: with self.assertWarns(DeprecationWarning): plistlib.writePlist(pl_in, fp) with open(support.TESTFN, "rb") as fp: with self.assertWarns(DeprecationWarning): pl2 = plistlib.readPlist(fp) self.assertEqual(pl_out, pl2)
def __init__(self, projectPath, unityProjectPath, plugins, testing = False): self.log("-------- Update Xcode Project --------") projectFile = projectPath + '/Unity-iPhone.xcodeproj/project.pbxproj' projectPlistPath = projectPath + '/Info.plist' self.infoPlist = plistlib.readPlist(projectPlistPath) self.p = XcodeProject.Load(projectFile) additionsFilePath = unityProjectPath + '/Assets/Editor/Gamedonia/plistAdditions.plist' if os.path.isfile(additionsFilePath): additionsPlist = plistlib.readPlist(additionsFilePath) for k in additionsPlist: if k != 'plistKeys': self.infoPlist[k] = additionsPlist[k] #Listamos las carpetas #plugins = get_immediate_subdirectories(unityProjectPath + '/Assets/Editor/') #self.log(plugins.count()) for pluginName in plugins if type(plugins) == type([]) else [plugins]: if pluginName != 'Gamedonia': self.run(pluginName, unityProjectPath + '/Assets/Editor/' + pluginName + '/') plistlib.writePlist(self.infoPlist, projectPlistPath) #Fix the path of the Frameworks headers search paths for b in self.p.get_build_phases('XCBuildConfiguration'): if b['buildSettings'].has_key('FRAMEWORK_SEARCH_PATHS'): self.log(' Has FRAMEWORK_SEARCH_PATHS!') spaths = []; spaths.append('$(inherited)') spaths.append('"' + unityProjectPath + '/Assets/Editor/**"') b['buildSettings']['FRAMEWORK_SEARCH_PATHS'] = spaths self.p.save()
def readConfig(configFile): config = readPlist(configFile + '.default') if os.path.exists(configFile): config.update(readPlist(configFile)) return config
def main(argv): args = argparse.ArgumentParser() args.add_argument('-w', '--write', action='store_true', help='write changes to files') args.add_argument('-p', '--path', help='override default journal entries path') args.add_argument('-l', '--location', help='country for which to check timezone entries', default='Japan') args.add_argument('-e', '--entry', help='print out single entry') flag = args.parse_args() base_dir = default_dir() if flag.path: if path.exists(flag.path): base_dir = path.expanduser(flag.path) else: print("path does not exist") exit() if flag.entry: filename = path.join(base_dir, str(flag.entry + '.doentry')) print(plistlib.readPlist(filename)) else: files = listdir(base_dir) files[:] = [file for file in files if file.endswith('.doentry')] for file in files: filename = path.join(base_dir, file) entry = plistlib.readPlist(filename) update = check_timezone(entry, flag.location) if update and flag.write: write_file(filename, update) print 'Done.'
def wificell_carve(): os.chdir('SystemConfiguration') plist_contents = {} for item in os.listdir('.'): print item if 'identif' in item: # gets executed first, then 'wifi' with open('wifi_cell_networks.txt', 'wa') as f: f.write('Networks: \n\n') ind = 1 plist_contents = pl.readPlist(item) for p in plist_contents['Signatures']: f.write('ID: ' + p['Identifier'] + '\n') for p2 in p['Services']: f.write('Addr: ' + p2['IPv4']['Router']+ '\n') f.write('\n') f.write('\n') ind += 1 if 'wifi' in item: with open('wifi_cell_networks.txt', 'a') as f: ind = 1 plist_contents = pl.readPlist(item) f.write('Wifi Networks:\n\n') f.write('SSID: ' + plist_contents['List of known networks'][0]['SSID_STR'] + '\n') f.write('BSSID: ' + plist_contents['List of known networks'][0]['BSSID'] + '\n') f.write('Secure?: ' + str(plist_contents['List of known networks'][0]['WiFiNetworkIsSecure']) + '\n') f.write('Password?: ' + str(plist_contents['List of known networks'][0]['WiFiNetworkRequiresPassword']) + '\n') f.write('Channel: ' + str(plist_contents['List of known networks'][0]['CHANNEL']) + '\n') f.write('\n') ind += 1 os.chdir(root_output_dir)
def main(): # Find the path to the Munki repository munkiimport_prefs_location=os.path.join(os.getenv("HOME"), "Library/Preferences/com.googlecode.munki.munkiimport.plist") if os.path.exists(munkiimport_prefs_location): munkiimport_prefs=plistlib.readPlist(munkiimport_prefs_location) MUNKI_ROOT_PATH=munkiimport_prefs['repo_path'] else: print "Cannot determine the Munki repo path. Be sure to run /usr/local/munki/munkiimport --configure to set the path for your user." sys.exit(1) # Variable for manifest path manifest_path=os.path.join(MUNKI_ROOT_PATH, manifest_subdir) # Check the path exists if not os.path.exists(manifest_path): print 'Manifest path %s does not exist' % manifest_path sys.exit(1) else: # Check the path is writable by the user running this script if not os.access(manifest_path, os.W_OK): print 'You do not have write access to the %s folder' % manifest_path sys.exit(1) else: print 'Using manifest path of %s' % manifest_path # Go through dictionary and process each key and value for new_man in manifest_translation: # Name old manifest old_man=manifest_translation[new_man] # Get full path to old manifest old_man_location=os.path.join(manifest_path, old_man) if not os.path.exists(old_man_location): print '%s does not exist' % old_man_location sys.exit(1) # Get the file ownership of the old manifest # Based on code from http://stackoverflow.com/a/927890 stat_info = os.stat(old_man_location) old_uid = stat_info.st_uid old_gid = stat_info.st_gid # Get the catalogs array from the old manifest old_manplist=plistlib.readPlist(old_man_location) old_catalogs=old_manplist['catalogs'] # Create new dictionary based on old catalogs and old name # Based on code from Munki's manifestutil manifest_dict = {'catalogs': old_catalogs, 'included_manifests': [old_man], 'managed_installs': [], 'managed_uninstalls': []} new_manifest_path = os.path.join(manifest_path, new_man) if os.path.exists(new_manifest_path): print '%s already exists!' % new_man else: print 'Creating %s to include %s with catalog(s) %s' % (new_man, old_man, old_catalogs) plistlib.writePlist(manifest_dict, new_manifest_path) # Make sure the ownership matches the old manifest os.chown(new_manifest_path, old_uid, old_gid)
def BuildPF(): CustomPrefList = buildlistdir("./Preferences") Plist = plistlib.readPlist('./BasePreferences.plist') Dict = { "cell": "PSGroupCell", "label": "Additional", "isStaticText": True } Plist["items"].append(Dict) Dict = { "cell": "PSSwitchCell", "label": "Log To The Console", "key": "LogToTheConsole", "default": False, "defaults": "naville.wtfjh" } Plist["items"].append(Dict)#Code-Signature Based Objc-Deobfuscation Confidence Dict = { "cell": "PSEditTextCell", "keyboard": "numbers", "placeholder": 0.8, "bestGuess":0.8, "isNumeric": True, "defaults": "naville.wtfjh" } Plist["items"].append(Dict) Dict = { "cell": "PSSwitchCell", "label": "URL Schemes Hooks", "key": "URLSchemesHooks", "default": False, "defaults": "naville.wtfjh" } Plist["items"].append(Dict) Dict = { "cell": "PSGroupCell", "label": "Modules", "isStaticText": True } Plist["items"].append(Dict) for x in ModuleList: CustomPrefPath = x + ".plist" if (CustomPrefPath in CustomPrefList): custom = plistlib.readPlist('./Preferences/' + CustomPrefPath) Plist["items"].append(custom) Dict = { "cell": "PSSwitchCell", "label": x, "key": x, "default": False, "defaults": "naville.wtfjh" } Plist["items"].append(Dict) Dict = { "cell": "PSGroupCell", "footerText": "https://github.com/Naville/WTFJH" } Plist["items"].append(Dict) plistlib.writePlist(Plist, "./layout/Library/PreferenceLoader/Preferences/WTFJHPreferences.plist")
def readConfig(config): """ Read useful information from the server's caldavd.plist file. @param config: file path to caldavd.plist @type config: str """ # SudoersFile was removed from the default caldavd.plist. Cope. plist = readPlist(config) try: plist["SudoersFile"] except KeyError: # add SudoersFile entry to caldavd.plist plist["SudoersFile"] = "/etc/caldavd/sudoers.plist" writePlist(plist,config) try: sudoerspl = readPlist('/etc/caldavd/sudoers.plist') except IOError: # create a new sudoers.plist with empty 'users' array sudoerspl = {'users': []} writePlist(sudoerspl,'/etc/caldavd/sudoers.plist') plist = readPlist(config) hostname = plist["ServerHostName"] serverroot = plist["ServerRoot"] docroot = plist["DocumentRoot"] docroot = os.path.join(serverroot, docroot) if docroot and docroot[0] not in ('/', '.',) else docroot sudoers = plist["SudoersFile"] port = plist["HTTPPort"] sslport = plist["SSLPort"] try: basic_ok = plist["Authentication"]["Basic"]["Enabled"] except KeyError: pass try: digest_ok = plist["Authentication"]["Digest"]["Enabled"] except KeyError: pass if basic_ok: authtype = "basic" elif digest_ok: authtype = "digest" if not hostname: hostname = "localhost" if docroot[0] != "/": docroot = base_dir + docroot if sudoers[0] != "/": sudoers = base_dir + sudoers return hostname, port, sslport, authtype, docroot, sudoers
def checkPlist(plistPath): if not os.path.exists(plistPath): raise FileNotFound try: readPlist(plistPath) except: return False return True
def generateTokens(): # Read this scripts plist try: # Read this scripts plist tokenPlist = plistlib.readPlist(plistFileFullPath) # Get the Refresh token from the plist refreshToken = tokenPlist["Refresh Token"] # If we can't find the plist except: # Try & generate new tokens try: # API call to generate tokens getTokens = requests.post( oauth2URL, data={ "grant_type": "authorization_code", "code": authorizationCode, "client_id": clientId, "client_secret": clientSecret, }, ) # If the above gives a 4XX or 5XX error getTokens.raise_for_status() # Get the JSON from the above newTokens = getTokens.json() # Get the new access token, valid for 60 minutes accessToken = newTokens["access_token"] # Log the access token we're using logging.info("Generated Access Token: %s" % accessToken) # Get the refresh token, valid for 60 days refreshToken = newTokens["refresh_token"] # Log the new refresh token we've generated logging.info("Generated Refresh Token: %s" % refreshToken) # Update plist with new refresh token & time generated, refresh token used for subsequent runs plistlib.writePlist( {"Refresh Token": refreshToken, "Time Generated": datetime.now().isoformat()}, plistFileFullPath ) # Update tokenPlist variable tokenPlist = plistlib.readPlist(plistFileFullPath) # If we cannot generate the tokens except requests.exceptions.RequestException, e: # Status message to use as subject for sendMail funtion statusMessage = "Cannot generate tokens %s" % e # Advise that no devices are to be deleted logging.error("-------- " + statusMessage + " --------") # Email & exit sendEmail(statusMessage) # If we cannot create the plist except: # Status message to use as subject for sendMail funtion statusMessage = "Cannot create plist" # Advise that no devices are to be deleted logging.error("-------- " + statusMessage + " --------") # Email & exit sendEmail(statusMessage)
def main(): munki_repo = get_repo() packages_in_repo = [] requirements_in_repo = [] for dirpath, dirnames, filenames in os.walk(os.path.join(munki_repo, "pkgsinfo")): for dirname in dirnames: # Skip directories that start with a period (e.g. ".git") if dirname.startswith("."): dirnames.remove(dirname) for filename in filenames: # Skip files that start with a period (e.g. ".DS_Store") if filename.startswith("."): continue filepath = os.path.join(dirpath, filename) try: pkginfo = plistlib.readPlist(filepath) try: if pkginfo["name"] not in packages_in_repo: if "update_for" not in pkginfo: if "installer_type" not in pkginfo: packages_in_repo.append(pkginfo["name"]) elif pkginfo["installer_type"] != "apple_update_metadata": packages_in_repo.append(pkginfo["name"]) if "requires" in pkginfo: for requirement in pkginfo["requires"]: if requirement not in requirements_in_repo: requirements_in_repo.append(requirement) except KeyError: continue except ExpatError: print >> sys.stderr, "Could not parse %s" % os.path.join( dirpath, filename) packages_in_manifests = [] for dirpath, dirnames, filenames in os.walk(os.path.join(munki_repo, "manifests")): for dirname in dirnames: # Skip directories that start with a period (e.g. ".git") if dirname.startswith("."): dirnames.remove(dirname) for filename in filenames: # Skip files that start with a period (e.g. ".DS_Store") if filename.startswith("."): continue filepath = os.path.join(dirpath, filename) try: manifest = plistlib.readPlist(filepath) process_manifest(manifest, packages_in_manifests) except ExpatError: print >> sys.stderr, "Could not parse %s" % os.path.join( dirpath, filename) unused_packages = list(set(packages_in_repo) - set(requirements_in_repo) - set(packages_in_manifests)) print "\n UNUSED PACKAGES:\n" pprint(unused_packages)
def merge(srcPath, dstPath): print('-- loading', srcPath) srcRoot = plistlib.readPlist(srcPath) srcMap = makeSrcMap(srcRoot) print('-- found', len(srcMap), 'tracks with metadata') print('-- loading', dstPath) dstRoot = plistlib.readPlist(dstPath) copyAttributes(dstRoot, srcMap)
def main(): parser = ArgumentParser(description=DESCR) parser.add_argument("file_a", help="First file") parser.add_argument("file_b", help="Second file") args = parser.parse_args() a = plistlib.readPlist(args.file_a) b = plistlib.readPlist(args.file_b) r = diff_value(a, b) pprint.pprint(r)
def _iphone_sdkroot(sdk, simulator): devroot = _iphone_devroot(simulator) if sdk is None: if simulator: info = plistlib.readPlist("/Developer/Platforms/iPhoneSimulator.platform/Info.plist") sdk = "iPhoneSimulator%s.sdk" % info["CFBundleShortVersionString"] else: info = plistlib.readPlist("/Developer/Platforms/iPhoneOS.platform/Info.plist") sdk = "iPhoneOS%s.sdk" % info["CFBundleShortVersionString"] return devroot / "SDKs" / sdk
def main(): #Don't run this yet.... enable in the end #subprocess.call(['/usr/sbin/networksetup', '-detectnewhardware']) # Check if the network is up success = False max_retries = 3 retries = 0 while retries < max_retries: print ip_addresses() if ip_addresses().strip() != "0": logger.info('Network connection is active. ') success = True break else: logger.info('No Connection Yet, trying again in 5 seconds') time.sleep(5) retries += 1 if not success: logger.critical('No Connection Available') sys.exit() download_file.downloadChunks(opts.plist_url,deploy_dir) plist_opts = plistlib.readPlist(config_plist) # Check if we're using a plist. # If there aren't packages and no plist (with packages in), bail plist_opts = {} plist_opts = plistlib.readPlist(config_plist) # Run over all of the packages and see if they look OK boot_scripts = plist_opts.get('Scripts') download_path = os.path.split(plist_url) download_path = download_path[0] print download_path logger.info('Downloading and Running:') logger.info('----------------------------------------------------------------') for script in boot_scripts: s = '/' scripts = download_path, script download = s.join(scripts) script_name = os.path.basename(script) logger.info ('Starting %s' % script_name ) logger.info ('--------') download_file.downloadChunks(download,script_dir) make_executable(script_dir + '/' + script_name) process = subprocess.Popen([script_dir + '/' + script_name]) process.wait() logger.info('Finished %s' % script_name) logger.info('--------') logger.info('----------------------------------------------------------------') script_number = len(boot_scripts) logger.info("Number Of Scripts: %s" % script_number) cleanup()
def _fix_plist(xcode_project_path): plist_path = os.path.join(xcode_project_path, 'Info.plist') try: f = open(plist_path, 'r') plistlib.readPlist(f) except Exception as e: s_out = [] with open(plist_path, 'r') as f: map(lambda x: s_out.append(x), [x for x in f.readlines() if x.strip() != '</string>']); with open(plist_path, 'w') as f: f.write(''.join(s_out))
def _iphone_sdkroot(sdk, simulator): devroot = _iphone_devroot(simulator) if sdk is None: if simulator: info = plistlib.readPlist( '/Developer/Platforms/iPhoneSimulator.platform/Info.plist') sdk = 'iPhoneSimulator%s.sdk' % info['CFBundleShortVersionString'] else: info = plistlib.readPlist( '/Developer/Platforms/iPhoneOS.platform/Info.plist') sdk = 'iPhoneOS%s.sdk' % info['CFBundleShortVersionString'] return devroot / 'SDKs' / sdk
def read_configfile(configfile=None): if configfile: try: conf = plistlib.readPlist(configfile) except IOError as e: sys.stderr.write("IOError: [Errno %d] %s: %s\n" % (e.errno, e.strerror, configfile)) sys.exit(1) except xml.parsers.expat.ExpatError as e: sys.stderr.write("Invalid file format: could not read configuration from %s.\n" % configfile) sys.exit(1) return plistlib.readPlist(configfile) else: return None
def find_cache_server(self): fallback_srv = 'http://localhost:49672' try: cmd = '/usr/bin/AssetCacheLocatorUtil' # self.log.info('Trying %s' % (cmd)) subprocess.Popen([cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE) except: self.log.debug('%s not on this system' % (cmd)) pass if os.path.exists(self.cache_config_path): try: self.cache_srv_conf = plistlib.readPlist( self.cache_config_path ) port = self.cache_srv_conf['Port'] self.cache_server = 'http://localhost:%s' % (port) self.log.debug( 'Local machine appears to be a Caching Server' ) except: self.cache_server = fallback_srv self.log.debug( 'Fallback Caching Server %s' % (self.cache_server) ) else: try: self.disk_cache, self.error = subprocess.Popen( ['/usr/bin/getconf DARWIN_USER_CACHE_DIR'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate() self.disk_cache = self.disk_cache.strip('\n') self.disk_cache = os.path.join( self.disk_cache, 'com.apple.AssetCacheLocatorService/diskCache.plist' ) self.log.debug( 'Using configuration from %s' % (self.disk_cache) ) plist = plistlib.readPlist(self.disk_cache) self.cache_server = ( plist['cache'][0]['servers'][0]['localAddressAndPort'] ) self.cache_server = 'http://%s' % (self.cache_server) except: self.cache_server = fallback_srv self.log.debug( 'Fallback Caching Server %s' % (self.cache_server) )
def testWrite(self): writer = UFOWriter(self.dstDir, formatVersion=2) writer.setKerningGroupConversionRenameMaps(self.downConversionMapping) writer.writeKerning(self.kerning) writer.writeGroups(self.groups) # test groups path = os.path.join(self.dstDir, "groups.plist") writtenGroups = readPlist(path) self.assertEqual(writtenGroups, self.expectedWrittenGroups) # test kerning path = os.path.join(self.dstDir, "kerning.plist") writtenKerning = readPlist(path) self.assertEqual(writtenKerning, self.expectedWrittenKerning) self.tearDownUFO()
def plist_load (self, filename): import plistlib fp = open(filename, 'rb') content = fp.read(8) fp.close() if content == 'bplist00': import warnings warnings.filterwarnings("ignore") tmpname = os.tempnam(None, 'plist.') plutil('-convert', 'xml1', '-o', tmpname, filename) data = plistlib.readPlist(tmpname) os.remove(tmpname) return data data = plistlib.readPlist(filename) return data
def on_post_save(self, view): """When a save occurs to a ThemeExtender extension, re-extend the theme""" # TODO: Uncomment section outside of dev # # If we are in the wrong directory, exit early # filepath = view.file_name() filepath = '/home/todd/.config/sublime-text-2/Packages/User/Theme Extender/Monokai Extended Bright.extended.tmTheme.plist' if not filepath.startswith(THEME_EXTENDER_FULL_FILEPATH): return # If the file is not an extension, exit early if not filepath.endswith('.plist'): return # TODO: Attempt to load the file as a plist print plistlib.readPlist(filepath)
def writeLocalCatalogs(applecatalogpath): '''Writes our local catalogs based on the Apple catalog''' catalog = plistlib.readPlist(applecatalogpath) # rewrite the URLs within the catalog to point to the items on our # local server instead of Apple's rewriteURLs(catalog) # remove the '.apple' from the end of the localcatalogpath if applecatalogpath.endswith('.apple'): localcatalogpath = applecatalogpath[0:-6] else: localcatalogpath = applecatalogpath print_stdout('Building %s...' % os.path.basename(localcatalogpath)) downloaded_products_list = getDownloadStatus() downloaded_products = {} product_keys = list(catalog['Products'].keys()) # filter Products, removing those that haven't been downloaded for product_key in product_keys: if product_key in downloaded_products_list: downloaded_products[product_key] = \ catalog['Products'][product_key] else: print_stderr('WARNING: did not add product %s to ' 'catalog %s because it has not been downloaded.', product_key, os.path.basename(applecatalogpath)) catalog['Products'] = downloaded_products # write raw (unstable/development) catalog # with all downloaded Apple updates enabled plistlib.writePlist(catalog, localcatalogpath) # now write filtered catalogs (branches) based on this catalog writeBranchCatalogs(localcatalogpath)
# Copyright 2014 Glossom, inc. All rights reserved. # import plistlib import sys argvs = sys.argv if argvs.count < 2: sys.exit() file_path = argvs[1] insert_scheme = argvs[2] found = False pl_bunleurltypes = [] pl = plistlib.readPlist(file_path) if pl.has_key("CFBundleURLTypes"): pl_bunleurltypes = pl["CFBundleURLTypes"] #check if scheme is already set for item in pl["CFBundleURLTypes"]: if item.has_key("CFBundleURLSchemes"): for scheme in item["CFBundleURLSchemes"]: if insert_scheme == scheme: found = True #set url scheme if not found: pl_bunleurltypes.append(dict({'CFBundleURLSchemes': [insert_scheme]})) pl["CFBundleURLTypes"] = pl_bunleurltypes plistlib.writePlist(pl, file_path)
def parse_loginitems(headers, output): user_loginitems_plist = multiglob(inputdir, [ 'Users/*/Library/Preferences/com.apple.loginitems.plist', 'private/var/*/Library/Preferences/com.apple.loginitems.plist' ]) for i in user_loginitems_plist: record = OrderedDict((h, '') for h in headers) metadata = stats2(i, oMACB=True) record.update(metadata) record['src_file'] = i record['src_name'] = "login_items" try: p = plistlib.readPlist(i) except: try: p = read_bplist(i) except: log.debug('Could not read plist {0}: {1}'.format( i, [traceback.format_exc()])) p = 'ERROR' if p != 'ERROR': items = p[0]['SessionItems']['CustomListItems'] for i in items: record['prog_name'] = i['Name'] if 'Alias' in i: try: alias_bin = i['Alias'] except: alias_bin = 'ERROR' if alias_bin != 'ERROR': c = [i.encode('hex') for i in alias_bin] for i in range(len(c)): l = int(c[i], 16) if l < len(c) and l > 2: test = os.path.join(inputdir, (''.join( c[i + 1:i + l + 1])).decode('hex')) try: if not os.path.exists(test): continue else: record['program'] = test cs_check_path = os.path.join( inputdir, test.lstrip('/')) record['code_signatures'] = str( get_codesignatures( cs_check_path, ncs)) except: continue record['program'] = 'ERROR' record['code_signatures'] = 'ERROR' elif 'Bookmark' in i: try: bookmark_bin = i['Bookmark'] except: bookmark_bin = 'ERROR' if bookmark_bin != 'ERROR': program = [i.encode('hex') for i in bookmark_bin] data = Bookmark.from_bytes( ''.join(program).decode('hex')) d = data.get(0xf081, default=None) d = ast.literal_eval(str(d).replace('Data', '')) if d is not None: prog = d.split(';')[-1].replace('\x00', '') record['program'] = prog cs_check_path = os.path.join( inputdir, prog.lstrip('/')) record['code_signatures'] = str( get_codesignatures(cs_check_path, ncs)) output.write_entry(record.values()) else: errors = { k: 'ERROR-CNR-PLIST' for k, v in record.items() if v == '' } record.update(errors)
import sys, os import plistlib urlScheme = sys.argv[1] bundleIdentifier = sys.argv[2] directory = os.path.dirname(os.path.abspath(__file__)) stringsOutput = os.path.join(directory, 'LLStrings.h') infoPlistOutput = os.path.join( directory, 'LaunchAtLoginHelper/LaunchAtLoginHelper-Info.plist') infoPlist = plistlib.readPlist( os.path.join(directory, 'LaunchAtLoginHelper/LaunchAtLoginHelper-InfoBase.plist')) with open(stringsOutput, 'w') as strings: strings.write("""// strings used by LLManager and LaunchAtLoginHelper // #define LLURLScheme @"%(urlScheme)s" #define LLHelperBundleIdentifier @"%(bundleIdentifier)s" """ % locals()) infoPlist['CFBundleIdentifier'] = bundleIdentifier plistlib.writePlist(infoPlist, infoPlistOutput)
def add_grammar(self, fp): grammar = Grammar(self, plistlib.readPlist(fp)) self._grammars[grammar.scope] = grammar return grammar
def generateProfile(path): """Generate an empty plist based upon the path given to a manifest.""" plist = plistlib.readPlist(path) result = {} generate(plist, result) return result, plist['pfm_domain']
def _reset_script_filters(self): """Load script filters from `info.plist`""" plistpath = self.wf.workflowfile('info.plist') # backup info.plist with open(plistpath, 'rb') as infile: with open(self.wf.workflowfile('info.plist.bak'), 'wb') as outfile: outfile.write(infile.read()) script_filters = {} plist = readPlist(plistpath) count = 0 keep = [] uids = set() for obj in plist['objects']: if obj.get('type') != 'alfred.workflow.input.scriptfilter': keep.append(obj) continue if obj.get('keyword') in RESERVED_KEYWORDS: keep.append(obj) continue script = obj.get('config', {}).get('script', '') log.debug('script : {!r}'.format(script)) m = SCRIPT_SEARCH(script) if not m: keep.append(obj) continue count += 1 uids.add(obj['uid']) # Overwrite objects minus script filters plist['objects'] = keep # Delete positioning data keep = {} uidata = plist['uidata'] for uid in uidata: if uid not in uids: keep[uid] = uidata[uid] # Overwrite without script filter positions plist['uidata'] = keep # Remove connections keep = {} connections = plist['connections'] for uid in connections: if uid not in uids: keep[uid] = connections[uid] # Overwrite without script filter connections plist['connections'] = keep # Re-write info.plist without script filters writePlist(plist, plistpath) log.debug('{} script filters deleted from info.plist'.format(count)) return script_filters
chdir='app-bundle') # Info.plist info_plist = test.built_file_path('Test App Gyp.app/Contents/Info.plist', chdir='app-bundle') test.must_exist(info_plist) test.must_contain(info_plist, 'com.google.Test-App-Gyp') # Variable expansion test.must_not_contain(info_plist, '${MACOSX_DEPLOYMENT_TARGET}') CheckFileXMLPropertyList(info_plist) if test.format != 'make': # TODO: Synthesized plist entries aren't hooked up in the make generator. machine = subprocess.check_output(['sw_vers', '-buildVersion']).rstrip('\n') plist = plistlib.readPlist(info_plist) ExpectEq(machine, plist['BuildMachineOSBuild']) # Prior to Xcode 5.0.0, SDKROOT (and thus DTSDKName) was only defined if # set in the Xcode project file. Starting with that version, it is always # defined. expected = '' if TestMac.Xcode.Version() >= '0500': version = TestMac.Xcode.SDKVersion() expected = 'macosx' + version ExpectEq(expected, plist['DTSDKName']) sdkbuild = TestMac.Xcode.SDKBuild() if not sdkbuild: # Above command doesn't work in Xcode 4.2. sdkbuild = plist['BuildMachineOSBuild'] ExpectEq(sdkbuild, plist['DTSDKBuild'])
def read_plist(self, filename): self.plist = plistlib.readPlist(filename)
def main(): MajorStr = "" MinorStr = "" BugfixStr = "" for line in fileinput.input(scriptpath + "/resource.h", inplace=0): if "#define PLUG_VER " in line: FullVersion = int(string.lstrip(line, "#define PLUG_VER "), 16) major = FullVersion & 0xFFFF0000 MajorStr = str(major >> 16) minor = FullVersion & 0x0000FF00 MinorStr = str(minor >> 8) BugfixStr = str(FullVersion & 0x000000FF) FullVersionStr = MajorStr + "." + MinorStr + "." + BugfixStr today = datetime.date.today() CFBundleGetInfoString = FullVersionStr + ", Copyright DanielLeonovPlugs, " + str( today.year) CFBundleVersion = FullVersionStr print "update_version.py - setting version to " + FullVersionStr print "Updating plist version info..." plistpath = scriptpath + "/resources/SubKicker-VST2-Info.plist" vst2 = plistlib.readPlist(plistpath) vst2['CFBundleGetInfoString'] = CFBundleGetInfoString vst2['CFBundleVersion'] = CFBundleVersion vst2['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(vst2, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") plistpath = scriptpath + "/resources/SubKicker-AU-Info.plist" au = plistlib.readPlist(plistpath) au['CFBundleGetInfoString'] = CFBundleGetInfoString au['CFBundleVersion'] = CFBundleVersion au['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(au, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") plistpath = scriptpath + "/resources/SubKicker-VST3-Info.plist" vst3 = plistlib.readPlist(plistpath) vst3['CFBundleGetInfoString'] = CFBundleGetInfoString vst3['CFBundleVersion'] = CFBundleVersion vst3['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(vst3, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") plistpath = scriptpath + "/resources/SubKicker-OSXAPP-Info.plist" app = plistlib.readPlist(plistpath) app['CFBundleGetInfoString'] = CFBundleGetInfoString app['CFBundleVersion'] = CFBundleVersion app['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(app, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") plistpath = scriptpath + "/resources/SubKicker-RTAS-Info.plist" rtas = plistlib.readPlist(plistpath) rtas['CFBundleGetInfoString'] = CFBundleGetInfoString rtas['CFBundleVersion'] = CFBundleVersion rtas['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(rtas, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") plistpath = scriptpath + "/resources/SubKicker-AAX-Info.plist" aax = plistlib.readPlist(plistpath) aax['CFBundleGetInfoString'] = CFBundleGetInfoString aax['CFBundleVersion'] = CFBundleVersion aax['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(aax, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") # plistpath = scriptpath + "/resources/SubKicker-IOSAPP-Info.plist" # iosapp = plistlib.readPlist(plistpath) # iosapp['CFBundleGetInfoString'] = CFBundleGetInfoString # iosapp['CFBundleVersion'] = CFBundleVersion # iosapp['CFBundleShortVersionString'] = CFBundleVersion # plistlib.writePlist(iosapp, plistpath) # replacestrs(plistpath, "//Apple//", "//Apple Computer//"); print "Updating Mac Installer version info..." plistpath = scriptpath + "/installer/SubKicker.pkgproj" installer = plistlib.readPlist(plistpath) for x in range(0, 6): installer['PACKAGES'][x]['PACKAGE_SETTINGS'][ 'VERSION'] = FullVersionStr plistlib.writePlist(installer, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") print "Updating Windows Installer version info..." for line in fileinput.input(scriptpath + "/installer/SubKicker.iss", inplace=1): if "AppVersion" in line: line = "AppVersion=" + FullVersionStr + "\n" sys.stdout.write(line)
payload_path = os.path.abspath(os.path.join(CURRENT_DIR, 'payload')) cmd = [PKGBUILD, '--analyze', '--root', payload_path, component_plist] try: returncode = subprocess.call(cmd) except OSError, err: raise BuildError( "pkgbuild execution failed with error code %d: %s" % (err.errno, err.strerror)) if returncode: raise BuildError( "pkgbuild failed with exit code %d: %s" % (returncode, " ".join(str(err).split()))) # Supress bundle relocation try: plist = plistlib.readPlist(component_plist) except ExpatError, err: raise BuildError("Couldn't read %s" % component_plist) # plist is an array of dicts, iterate through for bundle in plist: if bundle.get("BundleIsRelocatable"): bundle["BundleIsRelocatable"] = False display('Turning off bundle relocation for %s' % bundle['RootRelativeBundlePath']) try: plistlib.writePlist(plist, component_plist) except BaseException, err: raise BuildError("Couldn't write %s" % component_plist) return component_plist
import subprocess import sys if os.geteuid() != 0: os.execvp("sudo", ["sudo"] + sys.argv) interfacelist = subprocess.Popen(["/usr/sbin/networksetup","-listallhardwareports"], stdout=subprocess.PIPE).communicate()[0] try: interface = re.search('Wi-Fi\nDevice:\ (.+?)\n', interfacelist.decode()).group(1) except Exception as e: print( "Can't find wireless device, exiting...") print(str(e)) quit() try: networklist = plistlib.readPlist('/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist')["KnownNetworks"] except: print( "PList for Network is missing or no networks saved") quit() opennetworks = [] print( "====== List of preferred networks ======") for wifilist in networklist: wifi = networklist["{0}".format(wifilist)] print( "[-] Saved Network {0} - Encryption: {1}".format(wifi["SSID"].data, wifi["SecurityType"])) if (wifi["SecurityType"] == "Open"): opennetworks.append(wifi["SSID"].data) print( "\n")
def dict_from_plist(path): """Returns a dict based on plist found in path""" try: return plistlib.readPlist(path) except Exception, message: raise Exception("Error creating plist from output: %s" % message)
try: nbi = sys.argv[1] except: exit(1) actions = ["read", "write", "json"] try: action = sys.argv[2] if (action not in actions): exit(1) except: exit(1) plist = nbi + "/NBImageInfo.plist" try: plistObj = readPlist(plist) except: plistObj = { "Name": os.path.basename(nbi).replace('.nbi', ''), "Description": os.path.basename(nbi).replace('.nbi', ''), "Index": randint(1, 4095), "BootFile": "booter", "RootPath": ''.join([i for i in os.listdir(nbi) if i.endswith('.dmg')]), "IsEnabled": False, "IsInstall": False, "IsDefault": False, "Type": "HTTP", "Kind": 1, "Architectures": ["i386"] }
def main(): config = parse_config(projectpath) today = datetime.date.today() CFBundleGetInfoString = config['BUNDLE_NAME'] + " v" + config[ 'FULL_VER_STR'] + " " + config['PLUG_COPYRIGHT_STR'] CFBundleVersion = config['FULL_VER_STR'] print "update_version.py - setting version to " + config['FULL_VER_STR'] print "Updating plist version info..." plistpath = scriptpath + "/resources/SRChannel-VST2-Info.plist" vst2 = plistlib.readPlist(plistpath) vst2['CFBundleGetInfoString'] = CFBundleGetInfoString vst2['CFBundleVersion'] = CFBundleVersion vst2['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(vst2, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") plistpath = scriptpath + "/resources/SRChannel-AU-Info.plist" au = plistlib.readPlist(plistpath) au['CFBundleGetInfoString'] = CFBundleGetInfoString au['CFBundleVersion'] = CFBundleVersion au['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(au, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") plistpath = scriptpath + "/resources/SRChannel-VST3-Info.plist" vst3 = plistlib.readPlist(plistpath) vst3['CFBundleGetInfoString'] = CFBundleGetInfoString vst3['CFBundleVersion'] = CFBundleVersion vst3['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(vst3, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") plistpath = scriptpath + "/resources/SRChannel-macOS-Info.plist" app = plistlib.readPlist(plistpath) app['CFBundleGetInfoString'] = CFBundleGetInfoString app['CFBundleVersion'] = CFBundleVersion app['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(app, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") plistpath = scriptpath + "/resources/SRChannel-AAX-Info.plist" aax = plistlib.readPlist(plistpath) aax['CFBundleGetInfoString'] = CFBundleGetInfoString aax['CFBundleVersion'] = CFBundleVersion aax['CFBundleShortVersionString'] = CFBundleVersion plistlib.writePlist(aax, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") print "Updating Mac Installer version info..." plistpath = scriptpath + "/installer/SRChannel.pkgproj" installer = plistlib.readPlist(plistpath) for x in range(0, 5): installer['PACKAGES'][x]['PACKAGE_SETTINGS']['VERSION'] = config[ 'FULL_VER_STR'] plistlib.writePlist(installer, plistpath) replacestrs(plistpath, "//Apple//", "//Apple Computer//") print "Updating Windows Installer version info..." for line in fileinput.input(scriptpath + "/installer/SRChannel.iss", inplace=1): if "AppVersion" in line: line = "AppVersion=" + config['FULL_VER_STR'] + "\n" sys.stdout.write(line)
def parse_plist(path, source_root=None, allow_plist_update=True): """ Parse the reports from a plist file. One plist file can contain multiple reports. """ LOG.debug("Parsing plist: " + path) reports = [] files = [] try: plist = plistlib.readPlist(path) files = plist['files'] diag_changed = False for diag in plist['diagnostics']: available_keys = diag.keys() main_section = {} for key in available_keys: # Skip path it is handled separately. if key != 'path': main_section.update({key: diag[key]}) # We need to extend information for plist files generated # by older clang version (before 3.7). main_section['check_name'] = get_checker_name(diag, path) # We need to extend information for plist files generated # by older clang version (before 3.8). file_path = files[diag['location']['file']] if source_root: file_path = os.path.join(source_root, file_path.lstrip('/')) report_hash = get_report_hash(diag, file_path) main_section['issue_hash_content_of_line_in_context'] = \ report_hash if 'issue_hash_content_of_line_in_context' not in diag: # If the report hash was not in the plist, we set it in the # diagnostic section for later update. diag['issue_hash_content_of_line_in_context'] = report_hash diag_changed = True bug_path_items = [item for item in diag['path']] report = Report(main_section, bug_path_items, files) reports.append(report) if diag_changed and allow_plist_update: # If the diagnostic section has changed we update the plist file. # This way the client will always send a plist file where the # report hash field is filled. plistlib.writePlist(plist, path) except (ExpatError, TypeError, AttributeError) as err: LOG.error('Failed to process plist file: ' + path + ' wrong file format?') LOG.error(err) except IndexError as iex: LOG.error('Indexing error during processing plist file ' + path) LOG.error(type(iex)) LOG.error(repr(iex)) _, _, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) except Exception as ex: LOG.error('Error during processing reports from the plist file: ' + path) traceback.print_exc() LOG.error(type(ex)) LOG.error(ex) finally: return files, reports
def main(): argparser = ArgumentParser( description= 'Generate kerning samples by providing the left-hand side glyph') argparser.add_argument( '-u', dest='formatAsUnicode', action='store_const', const=True, default=False, help='Format output as unicode escape sequences instead of glyphnames. ' + 'E.g. "\\u2126" instead of "\\Omega"') argparser.add_argument('-prefix', dest='prefix', metavar='<text>', type=str, help='Text to append before each pair') argparser.add_argument('-suffix', dest='suffix', metavar='<text>', type=str, help='Text to append after each pair') argparser.add_argument( '-no-prefix-autocase', dest='noPrefixAutocase', action='store_const', const=True, default=False, help='Do not convert -prefix and -suffix to match case') argparser.add_argument( '-all-in-groups', dest='includeAllInGroup', action='store_const', const=True, default=False, help= 'Include all glyphs for groups rather than just the first glyph listed.' ) argparser.add_argument( '-left', dest='asLeft', action='store_const', const=True, default=False, help='Only include pairs where the glyphnames are on the left side.') argparser.add_argument( '-right', dest='asRight', action='store_const', const=True, default=False, help='Only include pairs where the glyphnames are on the right side.' + ' When neither -left or -right is provided, include all pairs.') argparser.add_argument('fontPath', metavar='<ufofile>', type=str, help='UFO font source') argparser.add_argument( 'glyphnames', metavar='<glyphname>', type=str, nargs='+', help='Name of glyphs to generate samples for. ' + 'You can also provide a Unicode code point using the syntax "U+XXXX"') args = argparser.parse_args() font = OpenFont(args.fontPath) groupsFilename = os.path.join(args.fontPath, 'groups.plist') kerningFilename = os.path.join(args.fontPath, 'kerning.plist') groups = plistlib.readPlist(groupsFilename) # { groupName => [glyphName] } kerning = plistlib.readPlist( kerningFilename) # { leftName => {rightName => kernVal} } groupmap = mapGroups(groups) # { glyphname => set(groupname, ...), ... } if not args.asLeft and not args.asRight: args.asLeft = True args.asRight = True # expand any unicode codepoints glyphnames = [] for glyphname in args.glyphnames: if len(glyphname) > 2 and glyphname[:2] == 'U+': cp = int(glyphname[2:], 16) ucmap = font.getCharacterMapping() # { 2126: ['Omega', ...], ...} for glyphname2 in ucmap[cp]: glyphnames.append(glyphname2) else: glyphnames.append(glyphname) for glyphname in glyphnames: if args.asLeft: samplesForGlyphnameL(font, groups, groupmap, kerning, glyphname, args) if args.asRight: samplesForGlyphnameR(font, groups, groupmap, kerning, glyphname, args)
def load(*args): global board; board = plistlib.readPlist("sav.plist"); redraw();
def main(): config = parse_config(projectpath) xcconfig = parse_xcconfig( os.path.join(os.getcwd(), IPLUG2_ROOT + '/common-mac.xcconfig')) CFBundleGetInfoString = config['BUNDLE_NAME'] + " v" + config[ 'FULL_VER_STR'] + " " + config['PLUG_COPYRIGHT_STR'] CFBundleVersion = config['FULL_VER_STR'] CFBundlePackageType = "BNDL" CSResourcesFileMapped = True LSMinimumSystemVersion = xcconfig['DEPLOYMENT_TARGET'] print "Copying resources ..." if config['PLUG_SHARED_RESOURCES']: dst = os.path.expanduser( "~") + "/Music/" + config['BUNDLE_NAME'] + "/Resources" else: dst = os.environ["TARGET_BUILD_DIR"] + os.environ[ "UNLOCALIZED_RESOURCES_FOLDER_PATH"] if os.path.exists(dst) == False: os.makedirs(dst + "/", 0755) if os.path.exists(projectpath + "/resources/img/"): imgs = os.listdir(projectpath + "/resources/img/") for img in imgs: print "copying " + img + " to " + dst shutil.copy(projectpath + "/resources/img/" + img, dst) if os.path.exists(projectpath + "/resources/fonts/"): fonts = os.listdir(projectpath + "/resources/fonts/") for font in fonts: print "copying " + font + " to " + dst shutil.copy(projectpath + "/resources/fonts/" + font, dst) print "Processing Info.plist files..." # VST3 plistpath = projectpath + "/resources/" + config[ 'BUNDLE_NAME'] + "-VST3-Info.plist" vst3 = plistlib.readPlist(plistpath) vst3['CFBundleExecutable'] = config['BUNDLE_NAME'] vst3['CFBundleGetInfoString'] = CFBundleGetInfoString vst3['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config[ 'BUNDLE_MFR'] + ".vst3." + config['BUNDLE_NAME'] + "" vst3['CFBundleName'] = config['BUNDLE_NAME'] vst3['CFBundleVersion'] = CFBundleVersion vst3['CFBundleShortVersionString'] = CFBundleVersion vst3['LSMinimumSystemVersion'] = LSMinimumSystemVersion vst3['CFBundlePackageType'] = CFBundlePackageType vst3['CFBundleSignature'] = config['PLUG_UNIQUE_ID'] vst3['CSResourcesFileMapped'] = CSResourcesFileMapped plistlib.writePlist(vst3, plistpath) # VST2 plistpath = projectpath + "/resources/" + config[ 'BUNDLE_NAME'] + "-VST2-Info.plist" vst2 = plistlib.readPlist(plistpath) vst2['CFBundleExecutable'] = config['BUNDLE_NAME'] vst2['CFBundleGetInfoString'] = CFBundleGetInfoString vst2['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config[ 'BUNDLE_MFR'] + ".vst." + config['BUNDLE_NAME'] + "" vst2['CFBundleName'] = config['BUNDLE_NAME'] vst2['CFBundleVersion'] = CFBundleVersion vst2['CFBundleShortVersionString'] = CFBundleVersion vst2['LSMinimumSystemVersion'] = LSMinimumSystemVersion vst2['CFBundlePackageType'] = CFBundlePackageType vst2['CFBundleSignature'] = config['PLUG_UNIQUE_ID'] vst2['CSResourcesFileMapped'] = CSResourcesFileMapped plistlib.writePlist(vst2, plistpath) # AUDIOUNIT v2 plistpath = projectpath + "/resources/" + config[ 'BUNDLE_NAME'] + "-AU-Info.plist" auv2 = plistlib.readPlist(plistpath) auv2['CFBundleExecutable'] = config['BUNDLE_NAME'] auv2['CFBundleGetInfoString'] = CFBundleGetInfoString auv2['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config[ 'BUNDLE_MFR'] + ".audiounit." + config['BUNDLE_NAME'] + "" auv2['CFBundleName'] = config['BUNDLE_NAME'] auv2['CFBundleVersion'] = CFBundleVersion auv2['CFBundleShortVersionString'] = CFBundleVersion auv2['LSMinimumSystemVersion'] = LSMinimumSystemVersion auv2['CFBundlePackageType'] = CFBundlePackageType auv2['CFBundleSignature'] = config['PLUG_UNIQUE_ID'] auv2['CSResourcesFileMapped'] = CSResourcesFileMapped if config['PLUG_TYPE'] == 0: if config['PLUG_DOES_MIDI_IN']: COMPONENT_TYPE = kAudioUnitType_MusicEffect else: COMPONENT_TYPE = kAudioUnitType_Effect elif config['PLUG_TYPE'] == 1: COMPONENT_TYPE = kAudioUnitType_MusicDevice elif config['PLUG_TYPE'] == 2: COMPONENT_TYPE = kAudioUnitType_MIDIProcessor auv2['AudioUnit Version'] = config['PLUG_VERSION_HEX'] auv2['AudioComponents'] = [{}] auv2['AudioComponents'][0]['description'] = config['PLUG_NAME'] auv2['AudioComponents'][0]['factoryFunction'] = config['AUV2_FACTORY'] auv2['AudioComponents'][0]['manufacturer'] = config['PLUG_MFR_ID'] auv2['AudioComponents'][0][ 'name'] = config['PLUG_MFR'] + ": " + config['PLUG_NAME'] auv2['AudioComponents'][0]['subtype'] = config['PLUG_UNIQUE_ID'] auv2['AudioComponents'][0]['type'] = COMPONENT_TYPE auv2['AudioComponents'][0]['version'] = config['PLUG_VERSION_INT'] auv2['AudioComponents'][0]['sandboxSafe'] = True plistlib.writePlist(auv2, plistpath) # AUDIOUNIT v3 if config['PLUG_HAS_UI']: NSEXTENSIONPOINTIDENTIFIER = "com.apple.AudioUnit-UI" else: NSEXTENSIONPOINTIDENTIFIER = "com.apple.AudioUnit" plistpath = projectpath + "/resources/" + config[ 'BUNDLE_NAME'] + "-macOS-AUv3-Info.plist" auv3 = plistlib.readPlist(plistpath) auv3['CFBundleExecutable'] = config['BUNDLE_NAME'] auv3['CFBundleGetInfoString'] = CFBundleGetInfoString auv3['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config[ 'BUNDLE_MFR'] + ".app." + config['BUNDLE_NAME'] + ".AUv3" auv3['CFBundleName'] = config['BUNDLE_NAME'] auv3['CFBundleVersion'] = CFBundleVersion auv3['CFBundleShortVersionString'] = CFBundleVersion auv3['LSMinimumSystemVersion'] = "10.12.0" auv3['CFBundlePackageType'] = "XPC!" auv3['NSExtension'] = dict( NSExtensionAttributes=dict(AudioComponentBundle="com.MattMontag.app." + config['BUNDLE_NAME'] + ".AUv3Framework", AudioComponents=[{}]), # NSExtensionServiceRoleType = "NSExtensionServiceRoleTypeEditor", NSExtensionPointIdentifier=NSEXTENSIONPOINTIDENTIFIER, NSExtensionPrincipalClass="IPlugAUViewController") auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'] = [{}] auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0][ 'description'] = config['PLUG_NAME'] auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0][ 'manufacturer'] = config['PLUG_MFR_ID'] auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0][ 'name'] = config['PLUG_MFR'] + ": " + config['PLUG_NAME'] auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0][ 'subtype'] = config['PLUG_UNIQUE_ID'] auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0][ 'type'] = COMPONENT_TYPE auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0][ 'version'] = config['PLUG_VERSION_INT'] auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0][ 'sandboxSafe'] = True auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0][ 'tags'] = [{}] if config['PLUG_TYPE'] == 1: auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0][ 'tags'][0] = "Synth" else: auv3['NSExtension']['NSExtensionAttributes']['AudioComponents'][0][ 'tags'][0] = "Effects" plistlib.writePlist(auv3, plistpath) # AAX plistpath = projectpath + "/resources/" + config[ 'BUNDLE_NAME'] + "-AAX-Info.plist" aax = plistlib.readPlist(plistpath) aax['CFBundleExecutable'] = config['BUNDLE_NAME'] aax['CFBundleGetInfoString'] = CFBundleGetInfoString aax['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config[ 'BUNDLE_MFR'] + ".aax." + config['BUNDLE_NAME'] + "" aax['CFBundleName'] = config['BUNDLE_NAME'] aax['CFBundleVersion'] = CFBundleVersion aax['CFBundleShortVersionString'] = CFBundleVersion aax['LSMinimumSystemVersion'] = LSMinimumSystemVersion aax['CSResourcesFileMapped'] = CSResourcesFileMapped plistlib.writePlist(aax, plistpath) # APP plistpath = projectpath + "/resources/" + config[ 'BUNDLE_NAME'] + "-macOS-Info.plist" macOSapp = plistlib.readPlist(plistpath) macOSapp['CFBundleExecutable'] = config['BUNDLE_NAME'] macOSapp['CFBundleGetInfoString'] = CFBundleGetInfoString macOSapp['CFBundleIdentifier'] = config['BUNDLE_DOMAIN'] + "." + config[ 'BUNDLE_MFR'] + ".app." + config['BUNDLE_NAME'] + "" macOSapp['CFBundleName'] = config['BUNDLE_NAME'] macOSapp['CFBundleVersion'] = CFBundleVersion macOSapp['CFBundleShortVersionString'] = CFBundleVersion macOSapp['LSMinimumSystemVersion'] = LSMinimumSystemVersion macOSapp['CFBundlePackageType'] = CFBundlePackageType macOSapp['CFBundleSignature'] = config['PLUG_UNIQUE_ID'] macOSapp['CSResourcesFileMapped'] = CSResourcesFileMapped macOSapp['NSPrincipalClass'] = "SWELLApplication" macOSapp['NSMainNibFile'] = config['BUNDLE_NAME'] + "-macOS-MainMenu" macOSapp['LSApplicationCategoryType'] = "public.app-category.music" macOSapp['CFBundleIconFile'] = config['BUNDLE_NAME'] + ".icns" # macOSapp['NSMicrophoneUsageDescription'] = "This app needs mic access to process audio." plistlib.writePlist(macOSapp, plistpath)
google_resource_bundle = path.join(target_google_framework_dir, 'GooglePlus.bundle') pbx_object.add_file_if_doesnt_exist(path.abspath(google_resource_bundle)) if using_twitter_sdk: for framework in twitter_frameworks: pbx_object.add_file_if_doesnt_exist(framework, tree='SDKROOT') for framework in weak_frameworks: pbx_object.add_file_if_doesnt_exist(framework, tree='SDKROOT', weak=True) pbx_object.add_other_ldflags('-ObjC') pbx_object.save() plist_data = plistlib.readPlist(os.path.join(build_path, 'Info.plist')) plist_data["iTunesAppID"] = itunes_app_id plist_types_arr = plist_data.get("CFBundleURLTypes") if plist_types_arr == None: plist_types_arr = [] plist_data["CFBundleURLTypes"] = plist_types_arr if using_twitter_sdk: twitter_schemes = { "CFBundleURLSchemes": ["tw{0}".format(twitter_consumer_key)] } plist_types_arr.append(twitter_schemes) if using_google_sdk:
def main(): plistlib.readPlist('TopSites.plist')
def manifest(cls): hashes_manifest_path = utilities.getlookupplistpath('hashes') hashes_manifest = plistlib.readPlist(hashes_manifest_path) return hashes_manifest
def get_os_level(): pl = plistlib.readPlist('/System/Library/CoreServices/SystemVersion.plist') v = pl['ProductVersion'] return '.'.join(v.split('.')[:2])
# Functions # 1. Open up different links to dash, daily, monthly, yearly # 2. Set API key, view graphs # 3. Get n most frequent events # 4. Get Focused import sys import subprocess # used for running bash commands import os # used for accessing env variables import requests # used for API requests import datetime import pyperclip from plistlib import readPlist, writePlist info = readPlist('info.plist') now = datetime.datetime.now() """ Run a linux command """ def shell(command): if not isinstance(command, list): command = [command] subprocess.check_output(command) """ url should be a list of arguments Example: url = ['ls', '-al']
def test_io(self): pl = self._create() plistlib.writePlist(pl, test_support.TESTFN) pl2 = plistlib.readPlist(test_support.TESTFN) self.assertEqual(dict(pl), dict(pl2))
def main(): demo = 0 if len(sys.argv) != 2: print("Usage: update_installer_version.py demo(0 or 1)") sys.exit(1) else: demo = int(sys.argv[1]) config = parse_config(projectpath) # MAC INSTALLER print "Updating Mac Installer version info..." plistpath = projectpath + "/installer/" + config['BUNDLE_NAME'] + ".pkgproj" installer = plistlib.readPlist(plistpath) # range = number of items in the installer (VST 2, VST 3, app, audiounit, aax) for x in range(0, 5): installer['PACKAGES'][x]['PACKAGE_SETTINGS']['VERSION'] = config[ 'FULL_VER_STR'] if demo: installer['PROJECT']['PROJECT_PRESENTATION']['TITLE']['LOCALIZATIONS'][ 0]['VALUE'] = config['BUNDLE_NAME'] + " Demo" installer['PROJECT']['PROJECT_PRESENTATION']['INTRODUCTION'][ 'LOCALIZATIONS'][0]['VALUE']['PATH'] = "intro-demo.rtf" else: installer['PROJECT']['PROJECT_PRESENTATION']['TITLE']['LOCALIZATIONS'][ 0]['VALUE'] = config['BUNDLE_NAME'] installer['PROJECT']['PROJECT_PRESENTATION']['INTRODUCTION'][ 'LOCALIZATIONS'][0]['VALUE']['PATH'] = "intro.rtf" plistlib.writePlist(installer, plistpath) # replacestrs(plistpath, "//Apple//", "//Apple Computer//"); # WIN INSTALLER print "Updating Windows Installer version info..." for line in fileinput.input(projectpath + "/installer/" + config['BUNDLE_NAME'] + ".iss", inplace=1): if "AppVersion" in line: line = "AppVersion=" + config['FULL_VER_STR'] + "\n" if "OutputBaseFilename" in line: if demo: line = "OutputBaseFilename=SRTestBed Demo Installer\n" else: line = "OutputBaseFilename=SRTestBed Installer\n" if 'Source: "readme' in line: if demo: line = 'Source: "readme-win-demo.rtf"; DestDir: "{app}"; DestName: "readme.rtf"; Flags: isreadme\n' else: line = 'Source: "readme-win.rtf"; DestDir: "{app}"; DestName: "readme.rtf"; Flags: isreadme\n' if "WelcomeLabel1" in line: if demo: line = "WelcomeLabel1=Welcome to the SRTestBed Demo installer\n" else: line = "WelcomeLabel1=Welcome to the SRTestBed installer\n" if "SetupWindowTitle" in line: if demo: line = "SetupWindowTitle=SRTestBed Demo installer\n" else: line = "SetupWindowTitle=SRTestBed installer\n" sys.stdout.write(line)
config_info = download location = config_info['request']['my_location'] user_info = config_info['info'] t = AutoDownload(config_info['app'], config_info['delay']) t.open() t.move(location['new_window']) t.move(location['create']) t.move(location['ip_input']) t.write(user_info['ip']) t.enter() t.move(location['user_input']) pyautogui.click() t.move(location['username']) t.write(user_info['username']) t.tab() t.write(user_info['password']) t.move(location['login']) t.move(location['report']) pyautogui.moveTo(location['restore report']) t.move(location['default']) t.move(location['download']) time.sleep(user_info['quit delay']) t.close() if __name__ == "__main__": try: main(plistlib.readPlist(config_path)) except IOError as e: print 'Error, Pls check'
def parse_LaunchAgentsDaemons(headers, output): LaunchAgents = multiglob(inputdir, [ 'System/Library/LaunchAgents/*.plist', 'Library/LaunchAgents/*.plist', 'Users/*/Library/LaunchAgents/*.plist', 'private/var/*/Library/LaunchAgents/*.plist', 'System/Library/LaunchAgents/.*.plist', 'Library/LaunchAgents/.*.plist', 'Users/*/Library/LaunchAgents/.*.plist', 'private/var/*/Library/LaunchAgents/.*.plist' ]) LaunchDaemons = multiglob(inputdir, [ 'System/Library/LaunchDaemons/*.plist', 'Library/LaunchDaemons/*.plist', 'System/Library/LaunchDaemons/.*.plist', 'Library/LaunchDaemons/.*.plist' ]) for i in LaunchDaemons + LaunchAgents: record = OrderedDict((h, '') for h in headers) metadata = stats2(i, oMACB=True) record.update(metadata) record['src_file'] = i record['src_name'] = "launch_items" try: p = plistlib.readPlist(i) except: try: p = read_bplist(i) except: log.debug('Could not read plist {0}: {1}'.format( i, [traceback.format_exc()])) p = 'ERROR' if p != 'ERROR': if type(p) is list and len(p) > 0: p = p[0] # Try to get Label from each plist. try: record['prog_name'] = p['Label'] except KeyError: log.debug("Cannot extract 'Label' from plist: {0}".format(i)) record['prog_name'] = 'ERROR' # Try to get ProgramArguments if present, or Program, from each plist. try: prog_args = p['ProgramArguments'] program = p['ProgramArguments'][0] record['program'] = program if len(prog_args) > 1: record['args'] = ' '.join(p['ProgramArguments'][1:]) except (KeyError, IndexError), e: try: program = p['Program'] record['program'] = program except: log.debug( "Cannot extract 'Program' or 'ProgramArguments' from plist: {0}" .format(i)) program = None record['program'] = 'ERROR' record['args'] = 'ERROR' except Exception, e: log.debug('Could not parse plist {0}: {1}'.format( i, [traceback.format_exc()])) program = None # If program is ID'd, run additional checks. if program: cs_check_path = os.path.join(inputdir, program.lstrip('/')) record['code_signatures'] = str( get_codesignatures(cs_check_path, ncs)) hashset = get_hashes(program) record['sha256'] = hashset['sha256'] record['md5'] = hashset['md5']
def panelExecutionState(debugKey, panelDebugValue=None): oldPanelDebugValue = 'err' CEPversion = 'CSXS.' + args.version # Windows: add HKEY_CURRENT_USER/Software/Adobe/CSXS.5 (add key) PlayerDebugMode [String] "1" if sys.platform == 'win32': def tryKey(key): try: return _winreg.QueryValueEx(key, debugKey) except: return None access = _winreg.KEY_READ if ( not panelDebugValue) else _winreg.KEY_ALL_ACCESS ky = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, "Software\\Adobe\\%s" % CEPversion, 0, access) keyValue = tryKey(ky) oldPanelDebugValue = '1' if keyValue and (keyValue[0] == '1') else '0' if (panelDebugValue): if not keyValue: _winreg.CreateKey(ky, debugKey) _winreg.SetValueEx(ky, debugKey, 0, _winreg.REG_SZ, panelDebugValue) _winreg.CloseKey(ky) # Mac: ~/Library/Preferences/com.adobe.CSXS.5.plist (add row) PlayerDebugMode [String] "1" elif sys.platform == "darwin": import subprocess, plistlib plistFile = os.path.expanduser( "~/Library/Preferences/com.adobe.%s.plist" % CEPversion) # First, make sure the Plist is in text format subprocess.check_output("plutil -convert xml1 " + plistFile, shell=True) plist = plistlib.readPlist(plistFile) oldPanelDebugValue = '1' if (plist.has_key(debugKey)) and ( plist[debugKey] == '1') else '0' if (panelDebugValue): plist[debugKey] = panelDebugValue plistlib.writePlist(plist, plistFile) # On Mac OS X 10.9 and higher, must reset the cfprefsd process # before changes in a plist file take effect macOSVer = [int(x) for x in platform.mac_ver()[0].split('.')] if (macOSVer[0] == 10) and (macOSVer[1] >= 9): proc = subprocess.Popen("ps ax | grep cfprefsd | grep -v grep", shell=True, stdout=subprocess.PIPE).stdout.read() procID = re.findall("^\s*(\d+)", proc, re.MULTILINE) if (procID): for p in procID: print "# MacOS 10.9: Killing cfprefsd process ID: " + p os.system("kill -HUP " + p) else: print "# MacOS 10.9: No cfprefsd process" else: print "Error: Unsupported platform: " + sys.platform sys.exit(0) return oldPanelDebugValue
def main(): argparser = ArgumentParser(description='Remove unused kerning') argparser.add_argument( '-dry', dest='dryRun', action='store_const', const=True, default=False, help='Do not modify anything, but instead just print what would happen.') argparser.add_argument( 'fontPaths', metavar='<ufofile>', type=str, nargs='+', help='UFO fonts to update') args = argparser.parse_args() dryRun = args.dryRun agl = loadAGL('src/glyphlist.txt') # { 2126: 'Omega', ... } diacriticComps = loadGlyphCompositions('src/diacritics.txt') # {glyphName => (baseName, a, o)} for fontPath in args.fontPaths: print(fontPath) groupsFilename = os.path.join(fontPath, 'groups.plist') kerningFilename = os.path.join(fontPath, 'kerning.plist') groups = plistlib.readPlist(groupsFilename) # { groupName => [glyphName] } kerning = plistlib.readPlist(kerningFilename) # { leftName => {rightName => kernVal} } font = OpenFont(fontPath) uc2names, name2ucs, allNames = loadLocalNamesDB([font], agl, diacriticComps) # start with eliminating non-existent glyphs from groups and completely # eliminate groups with all-dead glyphs. eliminatedGroups = set() for groupName, glyphNames in list(groups.items()): glyphNames2 = [] for name in glyphNames: if name in allNames: glyphNames2.append(name) else: name2 = canonicalGlyphName(name, uc2names) if name2 != name and name2 in allNames: print('group: rename glyph', name, '->', name2) glyphNames2.append(name2) if len(glyphNames2) == 0: print('group: eliminate', groupName) eliminatedGroups.add(groupName) del groups[groupName] elif len(glyphNames2) != len(glyphNames): print('group: shrink', groupName) groups[groupName] = glyphNames2 # now eliminate kerning groupRefs = RefTracker() # tracks group references, so we can eliminate unreachable ones for leftName, right in list(kerning.items()): leftIsGroup = leftName[0] == '@' if leftIsGroup: if leftName in eliminatedGroups: print('kerning: eliminate LHS', leftName) del kerning[leftName] continue groupRefs.incr(leftName) else: if leftName not in allNames: print('kerning: eliminate LHS', leftName) del kerning[leftName] continue right2 = {} for rightName, kernVal in right.iteritems(): rightIsGroup = rightName[0] == '@' if rightIsGroup: if rightIsGroup in eliminatedGroups: print('kerning: eliminate RHS group', rightName) else: groupRefs.incr(rightName) right2[rightName] = kernVal else: if rightName not in allNames: # maybe an unnamed glyph? rightName2 = canonicalGlyphName(rightName, uc2names) if rightName2 != rightName: print('kerning: rename & update RHS glyph', rightName, '->', rightName2) right2[rightName2] = kernVal else: print('kerning: eliminate RHS glyph', rightName) else: right2[rightName] = kernVal if len(right2) == 0: print('kerning: eliminate LHS', leftName) del kerning[leftName] if leftIsGroup: groupRefs.decr(leftName) else: kerning[leftName] = right2 # eliminate any unreferenced groups for groupName, glyphNames in list(groups.items()): if not groupName in groupRefs: print('group: eliminate unreferenced group', groupName) del groups[groupName] # verify that there are no conflicting kerning pairs pairs = {} # { key => [...] } conflictingPairs = set() for leftName, right in kerning.iteritems(): # expand LHS group -> names topLeftName = leftName for leftName in groups[leftName] if leftName[0] == '@' else [leftName]: if leftName not in allNames: raise Exception('unknown LHS glyph name ' + repr(leftName)) keyPrefix = leftName + '+' for rightName, kernVal in right.iteritems(): # expand RHS group -> names topRightName = rightName for rightName in groups[rightName] if rightName[0] == '@' else [rightName]: if rightName not in allNames: raise Exception('unknown RHS glyph name ' + repr(rightName)) # print(leftName, '+', rightName, '=>', kernVal) key = keyPrefix + rightName isConflict = key in pairs pairs.setdefault(key, []).append(( topLeftName, topRightName, kernVal )) if isConflict: conflictingPairs.add(key) # # resolve pair conflicts by preferring pairs defined via group kerning # for key in conflictingPairs: # pairs = pairs[key] # print('kerning: conflicting pairs %r: %r' % (key, pairs)) # bestPair = None # redundantPairs = [] # for pair in pairs: # leftName, rightName, kernVal = pair # if bestPair is None: # bestPair = pair # else: # bestLeftName, bestRightName, _ = bestPair # bestScore = 0 # score = 0 # if bestLeftName[0] == '@': bestScore += 1 # if bestRightName[0] == '@': bestScore += 1 # if leftName[0] == '@': score += 1 # if rightName[0] == '@': score += 1 # if bestScore == 2: # # doesn't get better than this # break # elif score > bestScore: # redundantPairs.append(bestPair) # bestPair = pair # else: # redundantPairs.append(pair) # print('- keeping', bestPair) # print('- eliminating', redundantPairs) # for redundantPairs # # eliminate any unreferenced groups # for groupName, glyphNames in list(groups.items()): # if not groupName in groupRefs: # print('group: eliminate unreferenced group', groupName) # del groups[groupName] print('Write', groupsFilename) if not dryRun: plistlib.writePlist(groups, groupsFilename) print('Write', kerningFilename) if not dryRun: plistlib.writePlist(kerning, kerningFilename)
def main(argv=None): """Main process.""" # Parse command line arguments. argparser = build_argument_parser() args = argparser.parse_args(argv) retval = 0 buildinfo = {} for filename in args.filenames: if filename.endswith(".plist"): try: buildinfo = plistlib.readPlist(filename) except (ExpatError, ValueError) as err: print("{}: plist parsing error: {}".format(filename, err)) retval = 1 break # no need to continue testing this file elif filename.endswith((".yaml", ".yml")): try: with open(filename, "r") as openfile: buildinfo = yaml.load(openfile) except Exception as err: print("{}: yaml parsing error: {}".format(filename, err)) retval = 1 break # no need to continue testing this file elif filename.endswith(".json"): try: with open(filename, "r") as openfile: buildinfo = json.load(openfile) except Exception as err: print("{}: json parsing error: {}".format(filename, err)) retval = 1 break # no need to continue testing this file if not buildinfo or not isinstance(buildinfo, dict): print("{}: cannot parse build-info file".format(filename)) retval = 1 break # Top level keys that all build-info files should contain. # NOTE: Even though other keys are listed as non-"optional" in the documentation, # name and version appear to be the only ones that are actually required. required_keys = ("name", "version") if not validate_required_keys(buildinfo, filename, required_keys): retval = 1 break # No need to continue checking this file if args.identifier_prefix: # Warn if the identifier does not start with the expected prefix. if not buildinfo.get("identifier", "").startswith( args.identifier_prefix): print("{}: identifier does not start " "with {}.".format(filename, args.identifier_prefix)) retval = 1 # Ensure buildinfo keys have expected types. if not validate_buildinfo_key_types(buildinfo, filename): retval = 1 # Warn if install_location is not the startup disk. if buildinfo.get("install_location") != "/": print("{}: WARNING: install_location is not set to the " "startup disk.".format(filename)) return retval