def createDmg(exportFileBaseName,appPath): import dmgbuild print 'creating dmg' os.chdir(os.path.abspath(os.path.join(__file__,os.path.pardir))) dmgbuild.build_dmg(exportFileBaseName,"Chataigne",settings_file = 'dmgbuild_conf.py',defines={'app':appPath}) print 'dmg done at :'+exportFileBaseName+'.dmg' return exportFileBaseName+'.dmg'
def dmgBuild(self): dmgFilename = str(self.appFile).replace(".app", "_rw.dmg") appName = self.appFile.name print(f"building dmg file: {dmgFilename}") # remove previous file if it's there if Path(dmgFilename).exists(): os.remove(dmgFilename) # then build new one icon = (thisFolder.parent / 'psychopy/app/Resources/psychopy.icns').resolve() background = (thisFolder / "dmg722x241.tiff").resolve() dmgbuild.build_dmg( filename=dmgFilename, volume_name=f'PsychoPy-{self.version}', # avoid spaces settings={ 'format': 'UDRW', 'files': [str(self.appFile)], 'symlinks': { 'Applications': '/Applications' }, 'size': '3g', # but maybe irrelevant in UDRW mode? 'badge_icon': str(icon), 'background': None, # background 'icon_size': 128, 'icon_locations': { 'PsychoPy.app': (150, 160), 'Applications': (350, 160) }, 'window_rect': ((600, 600), (500, 400)), }, ) print(f"building dmg file complete") sys.stdout.flush() return dmgFilename
def createDmg(self,exportFileBaseName): import dmgbuild print('creating dmg') os.chdir(os.path.abspath(os.path.join(__file__,os.path.pardir))) dmgbuild.build_dmg(exportFileBaseName,"Le Grand Mechant Loop",settings_file = 'dmgbuild_conf.py',defines={'app':self.getBinaryPath()}) print('dmg done at :'+exportFileBaseName+'.dmg') return exportFileBaseName+'.dmg'
def dmgBuild(self): dmgFilename = str(self.appFile).replace(".app", "_rw.dmg") print(f"building dmg file: {dmgFilename}") # remove previous file if it's there if Path(dmgFilename).exists(): os.remove(dmgFilename) # then build new one import dmgbuild icon = (thisFolder.parent / 'psychopy/app/Resources/psychopy.icns').resolve() background = (thisFolder / "builtin-arrow.tiff").resolve() dmgbuild.build_dmg( filename=dmgFilename, volume_name=f'PsychoPy {self.version}', settings={ 'format': 'UDRW', 'files': [str(thisFolder / 'dmg_settings.py')], 'symlinks': { 'Applications': '/Applications' }, 'size': '3m', # but maybe irrelevant in UDRW mode? 'badge_icon': str(icon), 'background': None, #"builtin-arrow", 'icon_size': 128, 'icon_locations': { 'dmg_settings.py': (150, 160), 'Applications': (350, 160) }, 'window_rect': ((600, 600), (500, 400)), }, ) self._dmgFile = dmgFilename return dmgFilename
def build_app(self): if self.dmg: print("Building DMG file...") dmg_name = self.formal_name.replace(' ', '_') + '.dmg' dmg_path = os.path.join(os.path.abspath(self.dir), dmg_name) dmgbuild.build_dmg(filename=dmg_path, volume_name=self.formal_name) return True
def createDmg(exportFileBaseName, appPath): import dmgbuild print 'creating dmg' os.chdir(os.path.abspath(os.path.join(__file__, os.path.pardir))) dmgbuild.build_dmg(exportFileBaseName, "Chataigne", settings_file='dmgbuild_conf.py', defines={'app': appPath}) print 'dmg done at :' + exportFileBaseName + '.dmg' return exportFileBaseName + '.dmg'
def create_dmg(): """ Create a dmg of the app """ # Check if app to exists if not os.path.isdir(APP_FILE): logger.error("Could not find app file at {}".format(APP_FILE)) sys.exit(1) DMG_FILE = os.path.join(OUTPUT_FOLDER, APP_NAME + u'.dmg') if os.path.exists(DMG_FILE): os.remove(DMG_FILE) print( "\n+++++++++++++++++++++ Creating DMG from app +++++++++++++++++++++++" ) # Get file size of APP APP_SIZE = subprocess.check_output(['du', '-sh', APP_FILE]).split()[0].decode('utf-8') # returns tuple with format ('3.0', 'G') (size, unit) = re.findall('(\d+\.?\d?)(\w)', APP_SIZE)[0] # Add a bit of extra to the disk image size APP_SIZE = str(float(size) * 1.25) + unit print("Creating disk image of {}".format(APP_SIZE)) # Create a dmgbuild config file in same folder as dmgbuild_config_file = os.path.join(os.getcwd(), 'dmgbuild_settings.py') dmg_config = { 'filename': DMG_FILE, 'volume_name': APP_NAME, 'size': APP_SIZE, 'files': [APP_FILE], 'symlinks': { 'Applications': '/Applications' }, } if ICON_FILE: dmg_config['badge_icon'] = ICON_PATH dmg_config['format'] = DMG_FORMAT dmg_config['icon_size'] = DMG_ICON_SIZE dmg_config['icon_locations'] = DMG_ICON_LOCATIONS dmg_config['window_rect'] = DMG_WINDOW_RECT write_vars_to_file(dmgbuild_config_file, dmg_config) print("Copying files to DMG and compressing it. Please wait.") dmgbuild.build_dmg(DMG_FILE, APP_NAME, settings_file=dmgbuild_config_file) # Clean up! os.remove(dmgbuild_config_file)
def make_disk_image(dist_dir, make_lite=False): """ Make macOS disk image containing Spyder.app application bundle. Parameters ---------- dist_dir : str Directory in which to put the disk image. make_lite : bool, optional Whether to append the disk image file and volume name with 'Lite'. The default is False. """ logger.info('Creating disk image...') from dmgbuild import build_dmg from dmgbuild.core import DMGError from spyder import __version__ as SPYVER from spyder.config.base import MAC_APP_NAME volume_name = '{}-{} Py-{}.{}.{}'.format(MAC_APP_NAME[:-4], SPYVER, *PYVER) dmgfile = os.path.join(dist_dir, 'Spyder') if make_lite: volume_name += ' Lite' dmgfile += '-Lite' dmgfile += '.dmg' settings_file = os.path.join(THISDIR, 'dmg_settings.py') settings = { 'files': [os.path.join(dist_dir, MAC_APP_NAME)], 'badge_icon': ICONFILE, 'icon_locations': { MAC_APP_NAME: (140, 120), 'Applications': (500, 120) } } try: build_dmg(dmgfile, volume_name, settings_file=settings_file, settings=settings, detach_retries=30) logger.info('Building disk image complete.') except DMGError as exc: if exc.args[0] == 'Unable to detach device cleanly': # don't raise this error since the dmg is forced to detach logger.warning(exc.args[0]) else: raise exc return
def buildDmg(self): """Build the DMG image.""" try: import dmgbuild except ImportError: raise OSError( 'Unable to import dmgbuild: please install the dmgbuild package.' ) if fexists(self.dmgName): os.unlink(self.dmgName) defines = { 'appname': APPNAME, 'files': [self.bundleDir], 'license_file': expandPath('@root/LICENSE'), 'icon_locations': { '{}.app'.format(APPNAME): (60, 50) }, } if self.applications_shortcut: defines['symlinks'] = {'Applications': '/Applications'} defines['icon_locations']['Applications'] = (60, 130) if self.volume_background: if not fexists(self.volume_background): raise OSError( 'DMG volume background image not found at {0}'.format( self.volume_background)) print('Using DMG volume background: {0}'.format( self.volume_background)) from PIL import Image w, h = Image.open(self.volume_background).size defines['background'] = self.volume_background defines['window_rect'] = ((100, 500), (str(w), (str(h)))) if self.volume_icon: if not fexists(self.volume_icon): raise OSError('DMG volume icon not found at {0}'.format( self.volume_icon)) print('Using DMG volume icon: {0}'.format(self.volume_icon)) defines['icon'] = self.volume_icon # Create the disk image using dmgbuild package. dmgbuild.build_dmg( self.dmgName, self.volume_label, settings_file=expandPath('@support/dmgbuild/settings.py'), defines=defines, )
def exe(): if platform.system() == 'Darwin': subprocess.run([sys.executable, 'setup.py', 'py2app'], check=True) import dmgbuild dmgbuild.build_dmg('dsremap-%s.dmg' % str(Meta.appVersion()), Meta.appName(), 'dmgbuild-settings.py') elif platform.system() == 'Windows': subprocess.run([sys.executable, 'setup.py', 'build'], check=True) distdir = r'build\exe.win-%s-%s' % (platform.machine().lower(), '%d.%d' % sys.version_info[:2]) with codecs.getwriter('utf-8')(open('installer.nsi', 'wb')) as dst: with codecs.getreader('utf-8')(open('installer.nsi.in', 'rb')) as src: for line in src: dst.write( line.replace('@APPNAME@', Meta.appName()).replace( '@APPVERSION@', str(Meta.appVersion())).replace( '@DISTDIR@', distdir).replace('@WEBSITE@', Meta.appSite())) import winreg key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE', 0, winreg.KEY_READ | winreg.KEY_WOW64_32KEY) try: path = winreg.QueryValue(key, 'NSIS') except: raise RuntimeError( 'Cannot find NSIS in registry, is it installed ?') finally: winreg.CloseKey(key) # Assuming NSIS 3.x here subprocess.run([ os.path.join(path, 'makensis.exe'), '/INPUTCHARSET', 'UTF8', 'installer.nsi' ], check=True) elif platform.system() == 'Linux': with codecs.getwriter('utf-8')(open('appimage.yml', 'wb')) as dst: with codecs.getreader('utf-8')(open('appimage.yml.in', 'rb')) as src: for line in src: dst.write(line.replace('@VERSION@', str(Meta.appVersion()))) subprocess.run( ['appimage-builder', '--recipe', 'appimage.yml', '--skip-test'], check=True) else: raise RuntimeError('Unsupported platform')
def build_app(self): print("Building DMG file...") dmg_name = self.formal_name + '.dmg' dmg_path = os.path.join(os.path.abspath(self.dir), dmg_name) dmgbuild.build_dmg( filename=dmg_path, volume_name=self.formal_name, settings={ 'files': [self.app_location], 'symlinks': {'Applications': '/Applications'}, 'background': self.background_image, 'icon': os.path.join(self.resource_dir, '%s.icns' % self.distribution.get_name()), } ) return True
def build_macos(): ''' Build DMG for macOS platform ''' execute([ sys.executable, '-m', 'PyInstaller', '--clean', '--noconfirm', 'counter.spec', ]) dmgbuild.build_dmg('dist/KeyCounter.dmg', 'KeyCounter', 'dmgbuild_conf.py', defines={}, lookForHiDPI=True)
def build_macos(): ''' Build DMG for macOS platform ''' execute([ sys.executable, '-m', 'PyInstaller', '--clean', '--noconfirm', 'counter.spec', ]) dmgbuild.build_dmg( 'dist/KeyCounter.dmg', 'KeyCounter', 'dmgbuild_conf.py', defines={}, lookForHiDPI=True )
async def main(): await scripting() os.chdir(payload) dmgbuild.build_dmg('chrome.dmg', 'Chrome App', 'settings.json') print("[+] Built Disk Image as Chrome.dmg") print("Notes: \n" "1) The created dmg file acts best as an update to a legitimate app (Chrome by default) \n" "2) Payload execution does not occur until the user runs the application (not just installation)") try: while True: pending = asyncio.Task.all_tasks() plist = [] for p in pending: if p._coro.__name__ != "main" and p._state == "PENDING": plist.append(p) if len(plist) == 0: exit(0) else: await asyncio.gather(*plist) except KeyboardInterrupt: pending = asyncio.Task.all_tasks() for t in pending: t.cancel()
def createDmg(self, exportFileBaseName): import dmgbuild import shutil print('creating dmg') betaSuffix = "" trueBinaryPath = self.getBinaryPath() if self.cfg["build_cfg_name"] == "Beta": betaBinaryPath = self.getBinaryPath().split( ".app")[0] + '_%s_Beta.app' % (self.getVersion()) shutil.copytree(trueBinaryPath, betaBinaryPath) trueBinaryPath = betaBinaryPath betaSuffix = "_Beta" # maxAppSize = str(self.getAppSize(trueBinaryPath)*1.3)+"b" dmgPath = exportFileBaseName + '_(%s)%s.dmg' % (self.getArchReadable(), betaSuffix) os.chdir(os.path.abspath(os.path.join(__file__, os.path.pardir))) dmgbuild.build_dmg(dmgPath, "Le Grand Mechant Loop", settings_file='dmgbuild_conf.py', defines={'app': trueBinaryPath}) print('dmg done at :' + dmgPath) return dmgPath
'window': { 'position': {'x': 400, 'y': 200}, 'size': {'width': 780, 'height': 480} }, 'contents': [ { 'x': 223, 'y': 227, 'type': 'file', 'path': app_path }, { 'x': 550, 'y': 227, 'type': 'link', 'path': '/Applications' } ] } json.dump(info, file) if __name__ == '__main__': console_print('generate dmg info') generate_dmg_info() console_print('build dmg: %s' % dmg_path) dmgbuild.build_dmg(dmg_path, app_name, dmg_settings_path) if not os.path.exists(dmg_path): console_print('fail to create %s' % dmg_path) sys.exit(1) sys.exit(0)
def test_sample_settings(): """Test with the sample settings.py file.""" dmgbuild.build_dmg('/tmp/out.dmg', 'Test', 'examples/settings.py') assert os.path.exists('/tmp/out.dmg')
# Copy Readme readmepath = os.path.join(apppath, "Contents/Resources/README.txt") # Path to background and the icon backgroundpath = "builder/osx/image/sabnzbd_new_bg.png" iconpath = "builder/osx/image/sabnzbdplus.icns" # Make DMG print("Building DMG") dmgbuild.build_dmg( filename=fileDmg, volume_name=prod, settings_file="builder/make_dmg.py", defines={ "app": apppath, "readme": readmepath, "background": backgroundpath, "iconpath": iconpath }, ) # Resign APP if authority: print("Siging DMG") os.system('codesign --deep -f -i "org.sabnzbd.SABnzbd" -s "%s" "%s"' % (authority, fileDmg)) print("Signed!") else: print("Signing skipped, missing SIGNING_AUTH.") exit()
def make_package(sourcesRoot, packagePath): buildDir = os.path.abspath( os.path.join(sourcesRoot, 'build_terminal', 'RelWithDebInfo')) binDir = os.path.join(buildDir, 'bin') packgeDir = os.path.join(buildDir, 'Blocksettle') if os.path.isdir(packgeDir): shutil.rmtree(packgeDir) elif os.path.exists(packgeDir): os.remove(packgeDir) if os.path.exists(packagePath): os.remove(packagePath) os.rename(binDir, packgeDir) pkgSettings = { "title": "Blocksettle Terminal", "background": "builtin-arrow", "format": "UDZO", "compression-level": 9, "window": { "position": { "x": 100, "y": 100 }, "size": { "width": 640, "height": 280 } }, "contents": [{ "x": 140, "y": 120, "type": "file", "path": packgeDir }, { "x": 500, "y": 120, "type": "link", "path": "/Applications" }] } # shutil.copyfile(os.path.join(sourcesRoot, 'Scripts', 'RFQBot.qml'), os.path.join(packgeDir, 'RFQBot.qml')) settingsFile = 'settings.json' if os.path.exists(settingsFile): os.remove(settingsFile) with open(settingsFile, 'w') as outfile: json.dump(pkgSettings, outfile) dmgbuild.build_dmg(packagePath, 'Blocksettle', settingsFile) if os.path.exists(packagePath): print('Package created: {}'.format(packagePath)) os.remove(settingsFile) return True else: print( 'Failed to create PKG file with settings: {}'.format(settingsFile)) return False
def main(): '''Parse command line input and run''' global scratchFolder # == process input import optparse parser = optparse.OptionParser() parser.add_option('-s', '--server-root', dest='serverRoot', default=None, help='path to the server component') parser.add_option('-i', '--install-path', dest='installPath', default=None, help='path to install to') parser.add_option('-o', '--ouptut-location', dest='outputPath', help='location for the output file') parser.add_option( '--rethinkdb-name', dest='binaryName', default='rethinkdb', help='name of the rethinkdb server binary') parser.add_option( '--signing-name', dest='signingName', default=None, help='signing identifier') parser.add_option( '--scratch-folder', dest='scratchFolder', default=None, help='folder for intermediate products') options, args = parser.parse_args() if len(args) > 0: parser.error('no non-keyword options are allowed') # = -s/--server-root if options.serverRoot is None: parser.error('-s/--server-root is required') if not os.path.isdir(options.serverRoot): parser.error('-s/--server-root must be a folder: %s' % options.serverRoot) options.serverRoot = os.path.realpath(options.serverRoot) # = get the version of rethinkdb # find the binary rethinkdbPath = os.path.join(options.serverRoot, options.binaryName) if not os.access(rethinkdbPath, os.X_OK): parser.error('No runnable RethinkDB executable at: %s' % rethinkdbPath) # get the version string versionString = '' try: command = [rethinkdbPath, '--version'] process = subprocess.Popen(command, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, _ = process.communicate() if process.returncode != 0: raise Exception() versionString = output.strip().split()[1].decode('utf-8') except Exception as e: print(e) parser.error('the executable given is not a valid RethinkDB executable: %s' % rethinkdbPath) strictVersion = re.match('^(\d+\.?)+(-\d+)?', versionString) if strictVersion is None: parser.error('version string from executable does not have a regular version string: %s' % versionString) strictVersion = strictVersion.group() # = -o/--ouptut-location if options.outputPath is None: options.outputPath = os.path.join(thisFolder, 'RethinkDB ' + versionString + '.dmg') elif os.path.isdir(options.outputPath): options.outputPath = os.path.join(options.outputPath, 'RethinkDB ' + versionString + '.dmg') elif not os.path.isdir(os.path.dirname(options.outputPath)): parser.error('the output path given is not valid: %s' % options.outputPath) # = --scratch-folder if options.scratchFolder is not None: options.scratchFolder = os.path.realpath(options.scratchFolder) parentDir = os.path.dirname(options.scratchFolder) if not os.path.isdir(parentDir): parser.error('The parent folder of --scratch-folder is not an existing folder: %s' % options.scratchFolder) if os.path.exists(options.scratchFolder) and not os.path.isdir(options.scratchFolder): parser.error('The --scratch-folder is not a folder: %s' % options.scratchFolder) elif not os.path.exists(options.scratchFolder): os.mkdir(options.scratchFolder) scratchFolder = options.scratchFolder # == build the pkg pkgPath = buildPackage(versionString, options.serverRoot, installPath=options.installPath, signingName=options.signingName) # == add dynamic content to settings dmgOptions = copy.deepcopy(defaultOptions) # = package dmgOptions['files'].append(pkgPath) dmgOptions['icon_locations'][os.path.basename(pkgPath)] = packagePosition # = uninstall script uninstallAppPath = compileUninstallApp(signingName=options.signingName) dmgOptions['files'].append(uninstallAppPath) # = release notes dmgOptions['files'].append(makeReleaseNotesLink(strictVersion)) # == dmg creation dmgbuild.build_dmg(options.outputPath, 'RethinkDB ' + versionString, defines=dmgOptions)
}, 'list_column_sort_directions': { 'name': 'ascending', 'date-modified': 'descending', 'date-created': 'descending', 'date-added': 'descending', 'date-last-opened': 'descending', 'size': 'descending', 'kind': 'ascending', 'label': 'ascending', 'version': 'ascending', 'comments': 'ascending', } } print("Creating image " + dmgFilename + "...", flush=True) dmgbuild.build_dmg(dmgFilename, dmgVolumeName, settings=dmgSettings) print("Done.", flush=True) filesToUpload.append(dmgFile) print("File size: " + str(dmgFile.stat().st_size) + "B", flush=True) # Upload artifacts if this is a Travis of GitHub Action build. # # We check for TRAVIS_REPO_SLUG rather than simply TRAVIS to prevent users # from mistakenly attempting to upload artifacts to our VGC servers if they # fork VGC and setup their own Travis builds. # # We have other security measures in place to prevent intentional harm from # malicious users. #
# tools tools_path = os.path.join(distpath, "ReplayTools") rmtree(tools_path, ignore_errors=True) os.makedirs(tools_path) copy(os.path.join(dirname, "tools", "FLIR-R440-ReplayTool-Wrapper.cmd"), tools_path) # demo replay tool r = os.system(sys.executable + " -m PyInstaller -a -y -F --noupx" + " --distpath " + os.path.join(distpath, 'ReplayTools') + " --workpath " + buildpath + " " + os.path.join(dirname, "tools","demo_replay.py")) if r: exit(r) # Translators r = os.system(sys.executable + " " + os.path.join(dirname, "translators", "create_translators_exe.py")) if r: exit(r) if platform.system() == "Darwin": import dmgbuild print("Creating App Bundle") translators_path = os.path.join(dirname, 'translators', 'dist') dmgbuild.build_dmg(volume_name="RASE", filename=os.path.join(distpath, "rase.dmg"), settings_file="dmgbuild_settings.py", settings={'files': [os.path.join(distpath, 'rase.app'), translators_path, tools_path, templatepath_name, basespectra_name]}, )
'-D', dest='defines', action='append', default=[], help='Define a value for the settings file (e.g. -Dfoo=bar).') parser.add_argument( '--no-hidpi', dest='lookForHiDPI', action='store_false', default=True, help= 'Do not search for HiDPI versions of the background image (if specified)') args = parser.parse_args() defines = {} for d in args.defines: k, v = d.split('=', 1) k = k.strip() v = v.strip() if (v.startswith("'") and v.endswith("'")) \ or (v.startswith('"') and v.endswith('"')): v = v[1:-1] defines[k] = v dmgbuild.build_dmg(args.filename, args.volume_name, args.settings, defines=defines, lookForHiDPI=args.lookForHiDPI)