Read `package.json` either from `resources.app.asar` (if the app is packaged)
or from `resources/app/package.json` (if it is not).
779041
function (options, callback) {
  var withAsar = path.join(options.src, 'resources/app.asar')
  var withoutAsar = path.join(options.src, 'resources/app/package.json')

  try {
    fs.accessSync(withAsar)
    options.logger('Reading package metadata from ' + withAsar)
    callback(null, JSON.parse(asar.extractFile(withAsar, 'package.json')))
    return
  } catch (err) {
  }

  try {
    options.logger('Reading package metadata from ' + withoutAsar)
    callback(null, fs.readJsonSync(withoutAsar))
  } catch (err) {
    callback(new Error('Error reading package metadata: ' + (err.message || err)))
  }
}
61457
def npm(package_json, output_file, pinned_file):
    """"""
    amd_build_deprecation_warning()
    try:
        version = get_distribution(current_app.name).version
    except DistributionNotFound:
        version = ''

    output = {
        'name': current_app.name,
        'version': make_semver(version) if version else version,
        'dependencies': {},
    }

    # Load base file
    if package_json:
        output = dict(output, **json.load(package_json))

    # Iterate over bundles
    deps = extract_deps(current_app.extensions['invenio-assets'].env,
                        click.echo)
    output['dependencies'].update(deps)

    # Load pinned dependencies
    if pinned_file:
        output['dependencies'].update(
            json.load(pinned_file).get('dependencies', {}))

    # Write to static folder if output file is not specified
    if output_file is None:
        if not os.path.exists(current_app.static_folder):
            os.makedirs(current_app.static_folder)
        output_file = open(
            os.path.join(current_app.static_folder, 'package.json'),
            'w')

    click.echo('Writing {0}'.format(output_file.name))
    json.dump(output, output_file, indent=4)
    output_file.close()
1109446
function getPackageSet(index, callback) {
	var page = {
		limit  : 100,
		offset : index*100
	}

	ckan.exec('current_package_list_with_resources', page, function(err, resp){
		checkError(err, resp);
		
		for( var i = 0; i < resp.result.length; i++ ) {
			data.packages[resp.result[i].id] = resp.result[i];
		}

		if( resp.result.length == 0 ) {
			if( callback ) callback();
		} else {
			if( options.debug ) console.log("CKAN EXPORT: Package data loaded ("+(index*100)+" to "+((index+1)*100)+")");
			index++;
			getPackageSet(index, callback);
		}
	});
}
758763
function (projectDir)
  {
    "use strict";
    const packageJson = readPackageJson(projectDir);
    const extracted = extractVendors(packageJson);

    return extracted.filter(function (packageName) { return startsWith(packageName, '@deskpro/'); });
  }
487178
function(next) {
            var files = [];
            if (core.appPackage && core.packages[core.appPackage]) files.push(core.packages[core.appPackage].path);
            files.push(core.home, core.path.etc + "/..", __dirname + "/..");
            for (var i in files) {
                var pkg = lib.readFileSync(files[i] + "/package.json", { json: 1, logger: "error", missingok: 1 });
                logger.debug("init:", files[i] + "/package.json", pkg.name, pkg.version);
                if (!core.appName && pkg.name) core.appName = pkg.name;
                if (!core.appVersion && pkg.version) core.appVersion = pkg.version;
                if (!core.appDescr && pkg.description) core.appDescr = pkg.description;
                if (!core.version && pkg.name == "backendjs") core.version = pkg.version;
            }
            if (!core.appName) core.appName = core.name;
            if (!core.appVersion) core.appVersion = core.version;
            // Use the app name as salt for consistentcy
            if (!core.salt) core.salt = lib.salt = core.appName;
            next();
        }
68538
def load_from_package():
    '''
    
    '''
    try:
        import pkg_resources
        f = pkg_resources.resource_stream(
            meta.__app__,
            'cache/unicategories.cache'
            )
        dversion, mversion, data = pickle.load(f)
        if dversion == data_version and mversion == module_version:
            return data
        warnings.warn(
            'Unicode unicategories database is outdated. '
            'Please reinstall unicategories module to regenerate it.'
            if dversion < data_version else
            'Incompatible unicategories database. '
            'Please reinstall unicategories module to regenerate it.'
            )
    except (ValueError, EOFError):
        warnings.warn(
            'Incompatible unicategories database. '
            'Please reinstall unicategories module to regenerate it.'
            )
    except (ImportError, FileNotFoundError):
        pass
1046268
function (params) {
        var self = this;
        this.parseParams(params);
        if (!this.loaded) {
          this.fetchApi(api).success(function (data) {
            packages = data;
            self.loaded = true;
            self.search();
          });
        }
        else {
          this.search();
        }
      }
1364176
function guessAppName (compilerWorkingDirectory) {
  var packageJson = path.resolve(compilerWorkingDirectory, 'package.json');
  if (!fs.existsSync(packageJson)) {
    packageJson = path.resolve(compilerWorkingDirectory, '../package.json');
    if (!fs.existsSync(packageJson)) {
      return 'Webpack App';
    }
  }
  return JSON.parse(fs.readFileSync(packageJson)).name;
}
1136380
function(context, pkg, source) {
		source = source || "{}";
		var packageJSON = JSON.parse(source);
		utils.extend(pkg, packageJSON);
		context.packages.push(pkg);
		return pkg;
	}
1121341
function() {
      var t = this;

      // Test an app directory to see if it's a monitor app
      var testAppDir = function(dir) {

        // Load the package.json if it exists (and remove relative refs)
        var pkg;
        dir = Path.resolve(dir);
        try {
          pkg = JSON.parse(FS.readFileSync(dir + '/package.json', 'utf-8'));
        } catch (e) {
          // Report an error if the package.json has a parse problem.  This is
          // good during app development to show why we didn't discover the app.
          if (e.code !== "ENOENT") {
             console.error("Problem parsing " + dir + "/package.json");
          }
          return false;
        }

        // Is this a monitor-dashboard app?
        var isMonitorApp = pkg.dependencies && _.find(_.keys(pkg.dependencies), function(keyword){ return keyword === 'monitor-dashboard'; });
        if (!isMonitorApp) {
          return false;
        }

        // This is a monitor-dashboard app.
        return t.loadApp(dir, pkg);
      };

      // Process all apps under a node_modules directory
      var loadNodeModulesDir = function(dir) {

        // Return if the node_modules directory doesn't exist.
        try {
          FS.statSync(dir);
        } catch (e) {return;}

        // Check each direcory for a monitor-dashboard app
        FS.readdirSync(dir).forEach(function(moduleName) {

          // See if this is a monitor app, and load if it is
          // then load sub-modules
          var moduleDir = dir + '/' + moduleName;
          if (testAppDir(moduleDir) || moduleName === 'monitor') {

            // If it is a monitor-app, process any sub node_modules
            loadNodeModulesDir(moduleDir + '/node_modules');
          }
        });
      };

      // Test this app as a monitor app
      t.thisAppName = testAppDir('.');

      // Process all possible node_module directories in the require path.
      process.mainModule.paths.forEach(loadNodeModulesDir);

    }
868623
def check_package(self, package, package_dir):
        """"""
        try:
            return self.packages_checked[package]
        except KeyError:
            pass

        init_py = orig.build_py.check_package(self, package, package_dir)
        self.packages_checked[package] = init_py

        if not init_py or not self.distribution.namespace_packages:
            return init_py

        for pkg in self.distribution.namespace_packages:
            if pkg == package or pkg.startswith(package + '.'):
                break
        else:
            return init_py

        with io.open(init_py, 'rb') as f:
            contents = f.read()
        if b'declare_namespace' not in contents:
            raise distutils.errors.DistutilsError(
                "Namespace package problem: %s is a namespace package, but "
                "its\n__init__.py does not call declare_namespace()! Please "
                'fix it.\n(See the setuptools manual under '
                '"Namespace Packages" for details.)\n"' % (package,)
            )
        return init_py
293258
function loadInfo() {
    try {
      var data = fs.readFileSync(__rootdir + '/package.json', { encoding: 'utf8' });
      var tmp = JSON.parse(data);
      appPackage = {
        name: tmp.name || null,
        version: tmp.version || 1
      }
    } catch(e) {
      return; // nothing to do.
    }
  }
1222420
def get_package(repo_url, pkg_name, timeout=1):
    """"""
    url = repo_url + "/packages/" + pkg_name
    headers = {'accept': 'application/json'}
    resp = requests.get(url, headers=headers, timeout=timeout)
    if resp.status_code == 404:
        return None
    return resp.json()
121802
function getPackageMetaFile(answers) {
    const packageFields = ['name', 'version', 'license', 'category'];
    const packageObject = merge(pick(packageFields, answers),
        { dependencies: { 'rung-cli': '1.0.0' } });

    return {
        filename: path.join(answers.name, 'package.json'),
        content: JSON.stringify(packageObject, null, 2)
    };
}
1204558
function handlePackage(packagePath) {
  // Read in the package.json.
  var packagePath = path.join(packagePath, 'package.json');
  try {
    var package = require(packagePath);
  } catch (e) {
    console.log('Skipping package ' + packagePath);
    return;
  }

  // Update dependencies as appropriate.
  if (package.dependencies && target in package['dependencies']) {
    package['dependencies'][target] = specifier;
  } else if (package.devDependencies && target in package['devDependencies']) {
    package['devDependencies'][target] = specifier;
  }

  // Write the file back to disk.
  fs.writeFileSync(packagePath, JSON.stringify(package, null, 2) + '\n');
}
1290776
def _load_package(self, json_line, installed_packages):
        
        if len(json_line) == 0:
            return {}, set([])

        valid_json = False
        try:
            user_package = json.loads(json_line)
            valid_json = True
        except ValueError:
            user_package = {}

        package_name = user_package['name'] if 'name' in user_package else None
        module_name = package_name.replace('-', '_') if package_name is not None else ''
        envs_before = set(registry.list())

        if not valid_json or package_name is None:
            self.cache_needs_update = True
            logger.warn('Unable to load user environments. Try deleting your cache '
                        'file "%s" if this problem persists. \n\nLine: %s', self.cache_path, json_line)
            return {}, set([])
        elif package_name not in installed_packages:
            self.cache_needs_update = True
            logger.warn('The package "%s" does not seem to be installed anymore. User environments from this '
                        'package will not be registered, and the package will no longer be loaded on `import gym`', package_name)
        elif module_name in sys.modules:
            self.cache_needs_update = True
            try:
                reload_module(sys.modules[module_name])
            except ImportError:
                if 'gym' in package_name:   # To avoid uninstalling failing dependencies
                    logger.warn('Unable to reload the module "%s" from package "%s" (%s). This is usually caused by a '
                                'invalid pip package. The package will be uninstalled and no longer be loaded on `import gym`.\n',
                                module_name, package_name, installed_packages[package_name])
                    traceback.print_exc(file=sys.stdout)
                    sys.stdout.write('\n')
                    self._run_cmd('{} uninstall -y {}'.format(pip_exec, package_name))
        else:
            try:
                __import__(module_name)
            except ImportError:
                if 'gym' in package_name:   # To avoid uninstalling failing dependencies
                    self.cache_needs_update = True
                    logger.warn('Unable to import the module "%s" from package "%s" (%s). This is usually caused by a '
                                'invalid pip package. The package will be uninstalled and no longer be loaded on `import gym`.\n',
                                module_name, package_name, installed_packages[package_name])
                    traceback.print_exc(file=sys.stdout)
                    sys.stdout.write('\n')
                    self._run_cmd('{} uninstall -y {}'.format(pip_exec, package_name))

        envs_after = set(registry.list())
        registered_envs = envs_after - envs_before
        if len(registered_envs) > 0:
            self.user_packages[package_name] = user_package
        for new_env in registered_envs:
            new_spec = registry.spec(new_env)
            new_spec.source = user_package['source']
            new_spec.package = '{} ({})'.format(user_package['name'], user_package['version'])
            self.env_ids.add(new_env.lower())
        return user_package, registered_envs
387717
def setup_package():
    """"""
    import json
    from setuptools import setup, find_packages

    filename_setup_json = 'setup.json'
    filename_description = 'README.md'

    with open(filename_setup_json, 'r') as handle:
        setup_json = json.load(handle)

    with open(filename_description, 'r') as handle:
        description = handle.read()

    setup(
        include_package_data=True,
        packages=find_packages(),
        setup_requires=['reentry'],
        reentry_register=True,
        long_description=description,
        long_description_content_type='text/markdown',
        **setup_json)