Create an srpm
    Requires that sources are available in local directory

    dist: set package dist tag (default: el7)
761900
def create_srpm(dist='el7'):
    
    if not RPM_AVAILABLE:
        raise RpmModuleNotAvailable()
    path = os.getcwd()
    try:
        specfile = spec_fn()
        spec = Spec(specfile)
    except Exception:
        return

    rpmdefines = ["--define 'dist .{}'".format(dist),
                  "--define '_sourcedir {}'".format(path),
                  "--define '_srcrpmdir {}'".format(path)]
    rpm.addMacro('_sourcedir', '.{}'.format(dist))
    # FIXME: needs to be fixed in Spec
    rpm.addMacro('dist', '.{}'.format(dist))
    module_name = spec.get_tag('Name', True)
    version = spec.get_tag('Version', True)
    release = spec.get_tag('Release', True)
    srpm = os.path.join(path,
                        "{}-{}-{}.src.rpm".format(module_name,
                                                  version,
                                                  release))

    # See if we need to build the srpm
    if os.path.exists(srpm):
        log.warn('Srpm found, rewriting it.')

    cmd = ['rpmbuild']
    cmd.extend(rpmdefines)

    cmd.extend(['--nodeps', '-bs', specfile])
    output = subprocess.check_output(' '.join(cmd), shell=True)
    log.warn(output)
    srpm = output.split()[1]
    return srpm
1053745
def _local_install(self, args, pkg_name=None):
        '''
        
        '''
        if len(args) < 2:
            raise SPMInvocationError('A package file must be specified')

        self._install(args)
888640
def build(force):
    
    dist_path = Path(DIST_PATH)
    if dist_path.exists() and list(dist_path.glob('*')):
        if force or click.confirm('{} is not empty - delete contents?'.format(dist_path)):
            dist_path.rename(DIST_PATH_DELETE)
            shutil.rmtree(Path(DIST_PATH_DELETE))
            dist_path.mkdir()
        else:
            click.echo('Aborting')
            sys.exit(1)

    subprocess.check_call(['python', 'setup.py', 'bdist_wheel'])
    subprocess.check_call(['python', 'setup.py', 'sdist',
                           '--formats=gztar'])
719424
def build_dist_from_args(ctx, dist, args):
    """"""
    bs = Bootstrap.get_bootstrap(args.bootstrap, ctx)
    blacklist = getattr(args, "blacklist_requirements", "").split(",")
    if len(blacklist) == 1 and blacklist[0] == "":
        blacklist = []
    build_order, python_modules, bs = (
        get_recipe_order_and_bootstrap(
            ctx, dist.recipes, bs,
            blacklist=blacklist
        ))
    assert set(build_order).intersection(set(python_modules)) == set()
    ctx.recipe_build_order = build_order
    ctx.python_modules = python_modules

    info('The selected bootstrap is {}'.format(bs.name))
    info_main('# Creating dist with {} bootstrap'.format(bs.name))
    bs.distribution = dist
    info_notify('Dist will have name {} and requirements ({})'.format(
        dist.name, ', '.join(dist.recipes)))
    info('Dist contains the following requirements as recipes: {}'.format(
        ctx.recipe_build_order))
    info('Dist will also contain modules ({}) installed from pip'.format(
        ', '.join(ctx.python_modules)))

    ctx.dist_name = bs.distribution.name
    ctx.prepare_bootstrap(bs)
    if dist.needs_build:
        ctx.prepare_dist(ctx.dist_name)

    build_recipes(build_order, python_modules, ctx, args.private,
                  ignore_project_setup_py=args.ignore_setup_py,
                 )

    ctx.bootstrap.run_distribute()

    info_main('# Your distribution was created successfully, exiting.')
    info('Dist can be found at (for now) {}'
         .format(join(ctx.dist_dir, ctx.dist_name)))
209025
def init():
    '''
    
    '''
    if not os.path.exists(__opts__['spm_cache_dir']):
        log.debug('Creating SPM cache directory at %s', __opts__['spm_db'])
        os.makedirs(__opts__['spm_cache_dir'])

    if not os.path.exists(__opts__['spm_db']):
        log.debug('Creating new package database at %s', __opts__['spm_db'])

    sqlite3.enable_callback_tracebacks(True)
    conn = sqlite3.connect(__opts__['spm_db'], isolation_level=None)

    try:
        conn.execute('SELECT count(*) FROM packages')
    except OperationalError:
        conn.execute('''CREATE TABLE packages (
            package text,
            version text,
            release text,
            installed text,
            os text,
            os_family text,
            dependencies text,
            os_dependencies text,
            os_family_dependencies text,
            summary text,
            description text
        )''')

    try:
        conn.execute('SELECT count(*) FROM files')
    except OperationalError:
        conn.execute('''CREATE TABLE files (
            package text,
            path text,
            size real,
            mode text,
            sum text,
            major text,
            minor text,
            linkname text,
            linkpath text,
            uname text,
            gname text,
            mtime text
        )''')

    return conn
609576
function build_dist_sourcemap(){
  // run webpack
  return gulp.src('index.js').pipe(webpackStream(createWebpackConfig({
    mode: 'development',
    entry: classicEntry,
    output: {
        filename:'oidc-client.js',
        libraryTarget:'var',
        library:'Oidc'
    },
    plugins: [],
    devtool:'inline-source-map'
  }), webpack))
  .pipe(gulp.dest('dist/'));
}
699136
function generate(spec) {
  createProjectDirectory();
  spec = addHttpEndpointNames(spec);
  spec = addSocketEndpointFlag(spec);
  spec = addSocketEmitTypeFlag(spec);
  spec = isProxyEndpointAvailable(spec);
  writeFileSync('server.mustache', spec, 'server.js');
  writeFileSync('package.mustache', spec, 'package.json');
}
623849
function createConfIndex() {
        requireConf.baseUrl = requireConf.baseUrl.replace(/\/$/, '') + '/';

        // create paths index
        pathsIndex = createKVSortedIndex(requireConf.paths);

        // create mappingId index
        mappingIdIndex = createKVSortedIndex(requireConf.map, 1);
        each(
            mappingIdIndex,
            function (item) {
                item.v = createKVSortedIndex(item.v);
            }
        );

        var lastMapItem = mappingIdIndex[mappingIdIndex.length - 1];
        if (lastMapItem && lastMapItem.k === '*') {
            each(
                mappingIdIndex,
                function (item) {
                    if (item != lastMapItem) {
                        item.v = item.v.concat(lastMapItem.v);
                    }
                }
            );
        }

        // create packages index
        packagesIndex = [];
        each(
            requireConf.packages,
            function (packageConf) {
                var pkg = packageConf;
                if (typeof packageConf === 'string') {
                    pkg = {
                        name: packageConf.split('/')[0],
                        location: packageConf,
                        main: 'main'
                    };
                }

                pkg.location = pkg.location || pkg.name;
                pkg.main = (pkg.main || 'main').replace(/\.js$/i, '');
                pkg.reg = createPrefixRegexp(pkg.name);
                packagesIndex.push(pkg);
            }
        );
        packagesIndex.sort(descSorterByKOrName);

        // create urlArgs index
        urlArgsIndex = createKVSortedIndex(requireConf.urlArgs, 1);

        // create bundles index
        bundlesIndex = {};
        /* eslint-disable no-use-before-define */
        function bundlesIterator(id) {
            bundlesIndex[resolvePackageId(id)] = key;
        }
        /* eslint-enable no-use-before-define */
        for (var key in requireConf.bundles) {
            each(requireConf.bundles[key], bundlesIterator);
        }
    }
757994
def build_package
      filename = config.tarball_filename(config.toml[:package][:version])
      relative_library_path = config.ruby_extension_path.sub("#{config.ruby_toplevel_dir}/", '')
      prepare_built_library
      Zlib::GzipWriter.open(filename) do |tgz|
        Dir.chdir(config.ruby_toplevel_dir) do
          Archive::Tar::Minitar.pack(relative_library_path, tgz)
        end
      end
    end
78803
def _build_tarball(src_repo) -> str:
    
    run = partial(subprocess.run, cwd=src_repo, check=True)
    run(['git', 'clean', '-xdff'])
    src_repo = Path(src_repo)
    if os.path.exists(src_repo / 'es' / 'upstream'):
        run(['git', 'submodule', 'update', '--init', '--', 'es/upstream'])
    run(['./gradlew', '--no-daemon', 'clean', 'distTar'])
    distributions = Path(src_repo) / 'app' / 'build' / 'distributions'
    return next(distributions.glob('crate-*.tar.gz'))
875161
def MakeDeployableBinary(self, template_path, output_path):
    """"""
    buildpackage_binary = "/usr/bin/dpkg-buildpackage"
    if not os.path.exists(buildpackage_binary):
      logging.error("dpkg-buildpackage not found, unable to repack client.")
      return

    with utils.TempDirectory() as tmp_dir:
      template_dir = os.path.join(tmp_dir, "dist")
      utils.EnsureDirExists(template_dir)

      zf = zipfile.ZipFile(template_path)
      for name in zf.namelist():
        dirname = os.path.dirname(name)
        utils.EnsureDirExists(os.path.join(template_dir, dirname))
        with open(os.path.join(template_dir, name), "wb") as fd:
          fd.write(zf.read(name))

      # Generate the dpkg files.
      self.GenerateDPKGFiles(tmp_dir)

      # Create a client config.
      client_context = ["Client Context"] + self.context
      client_config_content = self.GetClientConfig(client_context)

      # We need to strip leading /'s or .join will ignore everything that comes
      # before it.
      target_dir = config.CONFIG.Get(
          "ClientBuilder.target_dir", context=self.context).lstrip("/")
      agent_dir = os.path.join(
          template_dir, "debian",
          config.CONFIG.Get("ClientBuilder.package_name", context=self.context),
          target_dir)

      with open(
          os.path.join(
              agent_dir,
              config.CONFIG.Get(
                  "ClientBuilder.config_filename", context=self.context)),
          "wb") as fd:
        fd.write(client_config_content)

      # Set the daemon to executable.
      os.chmod(
          os.path.join(
              agent_dir,
              config.CONFIG.Get("Client.binary_name", context=self.context)),
          0o755)

      arch = config.CONFIG.Get("Template.arch", context=self.context)

      try:
        old_working_dir = os.getcwd()
      except OSError:
        old_working_dir = os.environ.get("HOME", "/tmp")

      try:
        os.chdir(template_dir)
        command = [buildpackage_binary, "-uc", "-d", "-b", "-a%s" % arch]

        try:
          subprocess.check_output(command, stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
          if "Failed to sign" not in e.output:
            logging.error("Error calling %s.", command)
            logging.error(e.output)
            raise

        filename_base = config.CONFIG.Get(
            "ClientBuilder.debian_package_base", context=self.context)
        output_base = config.CONFIG.Get(
            "ClientRepacker.output_basename", context=self.context)
      finally:
        try:
          os.chdir(old_working_dir)
        except OSError:
          pass

      utils.EnsureDirExists(os.path.dirname(output_path))

      for extension in [
          ".changes",
          config.CONFIG.Get(
              "ClientBuilder.output_extension", context=self.context)
      ]:
        input_name = "%s%s" % (filename_base, extension)
        output_name = "%s%s" % (output_base, extension)

        # TODO(user):pytype: incorrect move() definition in typeshed.
        # pytype: disable=wrong-arg-types
        shutil.move(
            os.path.join(tmp_dir, input_name),
            os.path.join(os.path.dirname(output_path), output_name))
        # pytype: enable=wrong-arg-types

      logging.info("Created package %s", output_path)
      return output_path
1219888
def makedirs_p(self, mode=0o777):
        
        with contextlib.suppress(FileExistsError):
            self.makedirs(mode)
        return self
1148938
function() {

			// origRepo is not defined if dist was skipped
			Release.dir.repo = Release.dir.origRepo || Release.dir.repo;
			return npmTags();
		}
758201
def makedirs_p(self, mode=0o777):
        
        try:
            self.makedirs(mode)
        except OSError:
            _, e, _ = sys.exc_info()
            if e.errno != errno.EEXIST:
                raise
        return self
798851
def setup_packages():
    '''
    
    '''

    # protect the user in case they run python setup.py not from root directory
    src_path = dirname(abspath(sys.argv[0]))
    old_path = os.getcwd()
    os.chdir(src_path)
    sys.path.insert(0, src_path)

    # create a list of the python extensions
    python_dirs = ["theory/python_bindings",
                   "mocks/python_bindings"]
    extensions = generate_extensions(python_dirs)

    # check requirement for extensions and set the compiler if specified
    # in command-line
    common_dict = requirements_check()

    # Some command options require headers/libs to be generated
    # so that the following dirs_patters supplies them.
    if install_required():
        from distutils.sysconfig import get_config_var
        if get_config_var('SHLIB_EXT') != '".so"' and version_info[0] == 2:
            msg = "The extensions all get the `.so` automatically. "\
                  "However, python expects the extension to be `{0}`"\
                  .format(get_config_var('SHLIB_EXT'))
            raise ValueError(msg)
        
        # global variable compiler is set if passed in
        # command-line
        extra_string = ''
        if compiler != '':
            extra_string = 'CC={0}'.format(compiler)

        command = "make libs {0}".format(extra_string)
        run_command(command)
        
    else:
        # not installing. Check if creating source distribution
        # in that case run distclean to delete auto-generated C
        # files
        if 'sdist' in sys.argv:
            command = "make distclean"
            run_command(command)
            

    # find all the data-files required.
    # Now the lib + associated header files have been generated
    # and put in lib/ and include/
    # This step must run after ``make install``
    dirs_patterns = {'theory/tests/data': ['*.ff', '*.txt',
                                              '*.txt.gz', '*.dat'],
                     'mocks/tests/data': ['*.ff', '*.txt',
                                             '*.txt.gz', '*.dat'],
                     'theory/tests': ['Mr19*', 'bins*', 'cmass*'],
                     'mocks/tests': ['Mr19*', 'bins*', 'angular_bins*'],
                     'include': ['count*.h'],
                     'lib': ['libcount*.a']
                     }
    data_files = []
    for d in dirs_patterns:
        patterns = dirs_patterns[d]
        f = recursive_glob(d, patterns)
        data_files.extend(f)

    # change them to be relative to package dir rather than root
    data_files = ["../{0}".format(d) for d in data_files]
    long_description = read_text_file('README.rst')
    min_np_major = int(common_dict['MIN_NUMPY_MAJOR'][0])
    min_np_minor = int(common_dict['MIN_NUMPY_MINOR'][0])

    # All book-keeping is done.
    # base_url = "https://github.com/manodeep/Corrfunc"
    classifiers = ['Development Status :: 4 - Beta',
                   'Intended Audience :: Developers',
                   'Intended Audience :: Science/Research',
                   'License :: OSI Approved :: MIT License',
                   'Natural Language :: English',
                   'Operating System :: POSIX',
                   'Programming Language :: C',
                   'Programming Language :: Python',
                   'Programming Language :: Python :: 2',
                   'Programming Language :: Python :: 2.7',
                   'Programming Language :: Python :: 3',
                   'Programming Language :: Python :: 3.4',
                   'Programming Language :: Python :: 3.5',
                   'Programming Language :: Python :: 3.6']
    metadata = dict(
            name=projectname,
            version=version,
            author='Manodeep Sinha',
            author_email='manodeep@gmail.com',
            maintainer='Manodeep Sinha',
            maintainer_email='manodeep@gmail.com',
            url=base_url,
            download_url='{0}/archive/{1}-{2}.tar.gz'.format(
                    base_url, projectname, version),
            description='Blazing fast correlation functions on the CPU',
            long_description=long_description,
            classifiers=classifiers,
            license='MIT',
            # Solaris might work, Windows will almost certainly not work
            platforms=["Linux", "Mac OSX", "Unix"],
            keywords=['correlation functions', 'simulations',
                      'surveys', 'galaxies'],
            provides=[projectname],
            packages=find_packages(),
            ext_package=projectname,
            ext_modules=extensions,
            package_data={'': data_files},
            include_package_data=True,
            setup_requires=['setuptools',
                            'numpy>={0}.{1}'.format(min_np_major,
                                                    min_np_minor)],
            install_requires=['numpy>={0}.{1}'.format(min_np_major,
                                                      min_np_minor),
                              'future',
                              'wurlitzer'],
            python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4',
            zip_safe=False,
            cmdclass={'build_ext': BuildExtSubclass})

    # Now the actual setup
    try:
        setup(**metadata)
    finally:
        del sys.path[0]
        os.chdir(old_path)

    return
1301215
def create_package(self):
        

        # Create the Lambda zip package (includes project and virtualenvironment)
        # Also define the path the handler file so it can be copied to the zip
        # root for Lambda.
        current_file = os.path.dirname(os.path.abspath(
            inspect.getfile(inspect.currentframe())))
        handler_file = os.sep.join(current_file.split(os.sep)[
                                   0:-2]) + os.sep + 'handler.py'
        exclude = self.zappa_settings[self.api_stage].get('exclude', []) + ['static', 'media']
        self.zip_path = self.zappa.create_lambda_zip(
                self.lambda_name,
                handler_file=handler_file,
                use_precompiled_packages=self.zappa_settings[self.api_stage].get('use_precompiled_packages', True),
                exclude=exclude
            )

        # Add this environment's Django settings to that zipfile
        with open(self.settings_file, 'r') as f:
            contents = f.read()
            all_contents = contents
            if not self.zappa_settings[self.api_stage].has_key('domain'):
                script_name = self.api_stage
            else:
                script_name = ''

            all_contents = all_contents + \
                '\n# Automatically added by Zappa:\nSCRIPT_NAME=\'/' + script_name + '\'\n'
            f.close()

        with open('zappa_settings.py', 'w') as f:
            f.write(all_contents)

        with zipfile.ZipFile(self.zip_path, 'a') as lambda_zip:
            lambda_zip.write('zappa_settings.py', 'zappa_settings.py')
            lambda_zip.close()

        os.unlink('zappa_settings.py')
1304424
def add_to_distribution(dist):
    """"""
    try:
        dist.add_qt_bindings()
    except AttributeError:
        raise ImportError("This script requires guidata 1.5+")
    for _modname in ('spyder', 'spyderplugins'):
        dist.add_module_data_files(_modname, ("", ),
                                   ('.png', '.svg', '.html', '.png', '.txt',
                                    '.js', '.inv', '.ico', '.css', '.doctree',
                                    '.qm', '.py',),
                                   copy_to_root=False)