This method creates CaseManager file and writes on it: the package, the
imports, its comments and the class name.

@param package_path
as es.upm.dit...
@param dest_dir
as src/main/java

@return the File with its first part written
@throws BeastException
491187
public static File startSystemCaseManager(String package_path,
            String dest_dir) throws BeastException {

        Logger logger = Logger
                .getLogger("CreateSystemCaseManager.startSystemCaseManager");

        File folder = SystemReader.createFolder(package_path, dest_dir);
        File caseManager = new File(folder, "UserStoriesManager.java");
        FileWriter caseManagerWriter;
        try {
            if (!caseManager.exists()) {
                caseManagerWriter = new FileWriter(caseManager);
                caseManagerWriter.write("package " + package_path + ";\n");
                caseManagerWriter.write("\n");
                caseManagerWriter.write("import org.junit.Assert;\n");
                caseManagerWriter.write("import org.junit.Test;\n");
                caseManagerWriter.write("import org.junit.runner.JUnitCore;\n");
                caseManagerWriter.write("import org.junit.runner.Result;\n");
                
                caseManagerWriter.write("\n");
                caseManagerWriter.write("/**\n");
                caseManagerWriter
                        .write(" * Main class to launch all tests in a single run\n");
                caseManagerWriter.write(" *\n");
                caseManagerWriter.write(" * @author es.upm.dit.gsi.beast\n");
                caseManagerWriter.write(" */\n");
                caseManagerWriter.write("public class UserStoriesManager {\n");
                caseManagerWriter.write("\n");
                caseManagerWriter.flush();
                caseManagerWriter.close();
                // logger.info("CaseManager has been created in "+dest_dir+Reader.createFolderPath(package_path));
            } else {
                List<String> lines = new ArrayList<String>();

                // read the file into lines
                BufferedReader r = new BufferedReader(new FileReader(
                        caseManager));
                String in;
                while ((in = r.readLine()) != null) {
                    lines.add(in);
                }
                r.close();

                lines.remove(lines.size() - 1);

                // write it back
                PrintWriter w = new PrintWriter(new FileWriter(caseManager));
                for (String line : lines) {
                    w.println(line);
                }
                w.close();
            }
        } catch (IOException e) {
            logger.severe("ERROR writing Case Manager file");
            throw new BeastException("ERROR writing Case Manager file", e);
        }

        return caseManager;
    }
761243
function (options, dir, callback) {
  var name = _.template('<%= id %>_<%= branch %>_<%= arch %>.flatpak')(options)
  var dest = options.rename(options.dest, name)
  options.logger('Creating package at ' + dest)
  var extraExports = []
  if (options.icon && !_.isObject(options.icon)) extraExports.push(getPixmapPath(options))

  var files = [
    [dir, '/']
  ]
  var symlinks = [
    [path.join('/lib', options.id, options.bin), path.join('/bin', options.bin)]
  ]

  flatpak.bundle({
    id: options.id,
    branch: options.branch,
    base: options.base,
    baseVersion: options.baseVersion,
    baseFlatpakref: options.baseFlatpakref,
    runtime: options.runtime,
    runtimeVersion: options.runtimeVersion,
    runtimeFlatpakref: options.runtimeFlatpakref,
    sdk: options.sdk,
    sdkFlatpakref: options.sdkFlatpakref,
    finishArgs: options.finishArgs,
    command: options.bin,
    files: files.concat(options.files),
    symlinks: symlinks.concat(options.symlinks),
    extraExports: extraExports,
    modules: options.modules
  }, {
    arch: options.arch,
    bundlePath: dest
  }, function (err) {
    callback(err, dir)
  })
}
767027
public static String createFolderPath(String path) {

        String[] pathParts = path.split("\\.");
        String path2 = "";
        for (String part : pathParts) {
            if (path2.equals("")) {
                path2 = part;
            } else {
                path2 = path2 + File.separator
                        + changeFirstLetterToLowerCase(createClassName(part));
            }
        }

        return path2;
    }
1105175
public void writeTo(Path directory) throws IOException {
    checkArgument(Files.notExists(directory) || Files.isDirectory(directory),
        "path %s exists but is not a directory.", directory);
    Path outputDirectory = directory;
    if (!packageName.isEmpty()) {
      for (String packageComponent : packageName.split("\\.")) {
        outputDirectory = outputDirectory.resolve(packageComponent);
      }
      Files.createDirectories(outputDirectory);
    }

    Path outputPath = outputDirectory.resolve(typeSpec.name + ".java");
    try (Writer writer = new OutputStreamWriter(Files.newOutputStream(outputPath), UTF_8)) {
      writeTo(writer);
    }
  }
585122
function modulePath(module, node_modules) {
  var pkgFile = path.join(node_modules, module, 'package.json');
  if (!fs.existsSync(pkgFile)) {
    return null;
  }
  var data = fs.readFileSync(pkgFile, 'utf8');
  var pkg = JSON.parse(data);
  var fileName = pkg.main || 'index.js';
  var filePath = path.join(node_modules, module, fileName);
  return realRequirPath(filePath);
}
398418
public void createPackageContents() {
		if (isCreated) return;
		isCreated = true;

		// Create classes and their features
		documentRootEClass = createEClass(DOCUMENT_ROOT);
		createEAttribute(documentRootEClass, DOCUMENT_ROOT__MIXED);
		createEReference(documentRootEClass, DOCUMENT_ROOT__XMLNS_PREFIX_MAP);
		createEReference(documentRootEClass, DOCUMENT_ROOT__XSI_SCHEMA_LOCATION);
		createEReference(documentRootEClass, DOCUMENT_ROOT__GLOBAL);
		createEReference(documentRootEClass, DOCUMENT_ROOT__IMPORT);
		createEReference(documentRootEClass, DOCUMENT_ROOT__META_DATA);
		createEReference(documentRootEClass, DOCUMENT_ROOT__ON_ENTRY_SCRIPT);
		createEReference(documentRootEClass, DOCUMENT_ROOT__ON_EXIT_SCRIPT);
		createEAttribute(documentRootEClass, DOCUMENT_ROOT__PACKAGE_NAME);
		createEAttribute(documentRootEClass, DOCUMENT_ROOT__PRIORITY);
		createEAttribute(documentRootEClass, DOCUMENT_ROOT__RULE_FLOW_GROUP);
		createEAttribute(documentRootEClass, DOCUMENT_ROOT__TASK_NAME);
		createEAttribute(documentRootEClass, DOCUMENT_ROOT__VERSION);

		globalTypeEClass = createEClass(GLOBAL_TYPE);
		createEAttribute(globalTypeEClass, GLOBAL_TYPE__IDENTIFIER);
		createEAttribute(globalTypeEClass, GLOBAL_TYPE__TYPE);

		importTypeEClass = createEClass(IMPORT_TYPE);
		createEAttribute(importTypeEClass, IMPORT_TYPE__NAME);

		metaDataTypeEClass = createEClass(META_DATA_TYPE);
		createEAttribute(metaDataTypeEClass, META_DATA_TYPE__META_VALUE);
		createEAttribute(metaDataTypeEClass, META_DATA_TYPE__NAME);

		onEntryScriptTypeEClass = createEClass(ON_ENTRY_SCRIPT_TYPE);
		createEAttribute(onEntryScriptTypeEClass, ON_ENTRY_SCRIPT_TYPE__SCRIPT);
		createEAttribute(onEntryScriptTypeEClass, ON_ENTRY_SCRIPT_TYPE__SCRIPT_FORMAT);

		onExitScriptTypeEClass = createEClass(ON_EXIT_SCRIPT_TYPE);
		createEAttribute(onExitScriptTypeEClass, ON_EXIT_SCRIPT_TYPE__SCRIPT);
		createEAttribute(onExitScriptTypeEClass, ON_EXIT_SCRIPT_TYPE__SCRIPT_FORMAT);

		// Create data types
		packageNameTypeEDataType = createEDataType(PACKAGE_NAME_TYPE);
		priorityTypeEDataType = createEDataType(PRIORITY_TYPE);
		ruleFlowGroupTypeEDataType = createEDataType(RULE_FLOW_GROUP_TYPE);
		taskNameTypeEDataType = createEDataType(TASK_NAME_TYPE);
		versionTypeEDataType = createEDataType(VERSION_TYPE);
	}
1372120
private ClassIndex doIndex(long timestamp, Path originalPath, Iterable<? extends Path> dirs) {
        Set<String> packages = new HashSet<>();
        Map<String, Collection<String>> classSimpleName2FQN = new HashMap<>();

        for (Path d : dirs) {
            try {
                Files.walkFileTree(d, new FileVisitor<Path>() {
                    int depth;
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                        waitIndexingNotSuspended();
                        if (depth++ == 0)
                            return FileVisitResult.CONTINUE;
                        String dirName = dir.getFileName().toString();
                        String sep = dir.getFileSystem().getSeparator();
                        dirName = dirName.endsWith(sep) ? dirName.substring(0, dirName.length() - sep.length())
                                                        : dirName;
                        if (SourceVersion.isIdentifier(dirName))
                            return FileVisitResult.CONTINUE;
                        return FileVisitResult.SKIP_SUBTREE;
                    }
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        waitIndexingNotSuspended();
                        if (file.getFileName().toString().endsWith(".class")) {
                            String relativePath = d.relativize(file).toString();
                            String binaryName = relativePath.substring(0, relativePath.length() - 6).replace('/', '.');
                            int packageDot = binaryName.lastIndexOf('.');
                            if (packageDot > (-1)) {
                                packages.add(binaryName.substring(0, packageDot));
                            }
                            String typeName = binaryName.replace('$', '.');
                            addClassName2Map(classSimpleName2FQN, typeName);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                    @Override
                    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                        return FileVisitResult.CONTINUE;
                    }
                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        depth--;
                        return FileVisitResult.CONTINUE;
                    }
                });
            } catch (IOException ex) {
                proc.debug(ex, "doIndex(" + d.toString() + ")");
            }
        }

        return new ClassIndex(timestamp, originalPath, packages, classSimpleName2FQN);
    }
1252970
def write_init_files(packages):
    
    init_text = """__path__ = __import__('pkgutil').extend_path(__path__, __name__)

try:
    from .__doc__ import __doc__
except ImportError:
    pass
"""
    for package in packages:
        path = os.path.join('src', package.replace('.', os.sep), '__init__.py')
        if os.path.exists(path):
            with open(path) as f:
                old_text = f.read()
        else:
            old_text = ''
        if old_text != init_text:
            with open(path, 'w') as f:
                f.write(init_text)
563543
def create_modules_toc_file(master_package, modules, opts, name='modules'):
    
    text = format_heading(1, '%s Modules' % opts.header)
    text += '.. toctree::\n'
    text += '   :maxdepth: %s\n\n' % opts.maxdepth

    modules.sort()
    prev_module = ''
    for module in modules:
        # look if the module is a subpackage and, if yes, ignore it
        if module.startswith(prev_module + '.'):
            continue
        prev_module = module
        text += '   %s\n' % module

    write_file(name, text, opts)
514348
public static void copyPackageInfo(final MetadataParserPath path, final Metadata metadata, final boolean verbose) throws IOException {
        for (final MetadataDescriptor descriptor : metadata.getMetadataDescriptorList()) {
            if (descriptor.getPathToPackageInfoApi() != null) {
                final File sourceFile = new File(descriptor.getPathToPackageInfoApi());
                final String destDirectory = path.pathToApi + File.separatorChar + descriptor.getPackageApi().replace('.', '/');
                deleteExistingPackageInfo(destDirectory, verbose);
                copy(sourceFile, destDirectory, verbose);
            }

            if (descriptor.getPathToPackageInfoImpl() != null) {
                final File sourceFile = new File(descriptor.getPathToPackageInfoImpl());
                final String destDirectory = path.pathToImpl + File.separatorChar + descriptor.getPackageImpl().replace('.', '/');
                deleteExistingPackageInfo(destDirectory, verbose);
                copy(sourceFile, destDirectory, verbose);
            }
        }
    }
414255
protected void generatePackageTreeFile() throws DocFileIOException {
        HtmlTree body = getPackageTreeHeader();
        HtmlTree htmlTree = (configuration.allowTag(HtmlTag.MAIN))
                ? HtmlTree.MAIN()
                : body;
        Content headContent = contents.getContent("doclet.Hierarchy_For_Package",
                utils.getPackageName(packageElement));
        Content heading = HtmlTree.HEADING(HtmlConstants.TITLE_HEADING, false,
                HtmlStyle.title, headContent);
        Content div = HtmlTree.DIV(HtmlStyle.header, heading);
        if (configuration.packages.size() > 1) {
            addLinkToMainTree(div);
        }
        htmlTree.addContent(div);
        HtmlTree divTree = new HtmlTree(HtmlTag.DIV);
        divTree.addStyle(HtmlStyle.contentContainer);
        addTree(classtree.baseClasses(), "doclet.Class_Hierarchy", divTree);
        addTree(classtree.baseInterfaces(), "doclet.Interface_Hierarchy", divTree);
        addTree(classtree.baseAnnotationTypes(), "doclet.Annotation_Type_Hierarchy", divTree);
        addTree(classtree.baseEnums(), "doclet.Enum_Hierarchy", divTree, true);
        htmlTree.addContent(divTree);
        if (configuration.allowTag(HtmlTag.MAIN)) {
            body.addContent(htmlTree);
        }
        HtmlTree tree = (configuration.allowTag(HtmlTag.FOOTER))
                ? HtmlTree.FOOTER()
                : body;
        addNavLinks(false, tree);
        addBottom(tree);
        if (configuration.allowTag(HtmlTag.FOOTER)) {
            body.addContent(tree);
        }
        printHtmlDocument(null, true, body);
    }
910599
def extract_lambda_package(self, package_name, path):
        
        lambda_package = lambda_packages[package_name][self.runtime]

        # Trash the local version to help with package space saving
        shutil.rmtree(os.path.join(path, package_name), ignore_errors=True)

        tar = tarfile.open(lambda_package['path'], mode="r:gz")
        for member in tar.getmembers():
            tar.extract(member, path)
282401
def create_package_file(root, master_package, subroot, py_files, opts, subs):
    """"""
    package = os.path.split(root)[-1]
    text = format_heading(1, '%s Package' % package)
    # add each package's module
    for py_file in py_files:
        if shall_skip(os.path.join(root, py_file)):
            continue
        is_package = py_file == INIT
        py_file = os.path.splitext(py_file)[0]
        py_path = makename(subroot, py_file)
        if is_package:
            heading = ':mod:`%s` Package' % package
        else:
            heading = ':mod:`%s` Module' % py_file
        text += format_heading(2, heading)
        text += format_directive(is_package and subroot or py_path, master_package)
        text += '\n'

    # build a list of directories that are packages (they contain an INIT file)
    subs = [sub for sub in subs if os.path.isfile(os.path.join(root, sub, INIT))]
    # if there are some package directories, add a TOC for theses subpackages
    if subs:
        text += format_heading(2, 'Subpackages')
        text += '.. toctree::\n\n'
        for sub in subs:
            text += '    %s.%s\n' % (makename(master_package, subroot), sub)
        text += '\n'

    write_file(makename(master_package, subroot), text, opts)
1027418
def packageFromPath(path, includeModule=False):
    
    path = nstr(path)
    module = ''
    if os.path.isfile(path):
        path, fname = os.path.split(path)
        if fname.endswith('.py') and fname != '__init__.py':
            module = fname.split('.')[0]

    parts = os.path.normpath(path).split(os.path.sep)
    package_parts = []

    for i in range(len(parts), 0, -1):
        filename = os.path.sep.join(parts[:i] + ['__init__.py'])

        if not os.path.isfile(filename):
            break

        package_parts.insert(0, parts[i - 1])

    if includeModule and module:
        package_parts.append(module)

    return '.'.join(package_parts)
392102
def packageRootPath(path):
    
    path = nstr(path)
    if os.path.isfile(path):
        path = os.path.dirname(path)

    parts = os.path.normpath(path).split(os.path.sep)
    package_parts = []

    for i in range(len(parts), 0, -1):
        filename = os.path.sep.join(parts[:i] + ['__init__.py'])

        if not os.path.isfile(filename):
            break

        package_parts.insert(0, parts[i - 1])

    if not package_parts:
        return path
    return os.path.abspath(os.path.sep.join(parts[:-len(package_parts)]))
888815
private function initPackageClassPhp($path, $packageName)
    {
        $class = $this->getClass($packageName);
        $namespace = $this->getNamespace($packageName);
        $file = $path.'/src/'.$class.'.php';
        if (file_exists($file)) {
            return;
        }
        $code = file_get_contents(__DIR__.'/../../tpl/PackageClass.php.txt');
        $code = str_replace(['%%CLASS%%', '%%NAMESPACE%%'], [$class, $namespace], $code);
        if (!is_dir($path.'/src')) {
            mkdir($path.'/src');
        }
        file_put_contents($file, $code);
    }
499053
protected static FileWriter createFileWriter(String scenarioName,
            String aux_package_path, String dest_dir) throws BeastException {
        try {
            return new FileWriter(new File(createFolder(aux_package_path,
                    dest_dir), scenarioName + ".story"));
        } catch (IOException e) {
            String message = "ERROR writing the " + scenarioName
                    + ".story file: " + e.toString();
            logger.severe(message);
            throw new BeastException(message, e);
        }
    }