Create symlink into project module directory

@return void

@throws \Exception : If remove symlink fail with the reinstall option
487192
protected function createSymbolicLink()
    {
        $this->displayMsgInCli(' > Create symbolic link ... ');

        $alreadyCreated = file_exists($this->targetSrcPath);

        //If symlink already exist and it's a reinstall mode
        if ($alreadyCreated && $this->forceReinstall === true) {
            $this->displayMsgInCli('[Force Reinstall: Remove symlink] ');
            $alreadyCreated = false;

            //Error with remove symlink
            if (!unlink($this->targetSrcPath)) {
                $this->displayMsgNLInCli('Symbolic link remove fail.', 'red', 'bold');
                
                throw new Exception(
                    'Reinstall fail. Symlink remove error',
                    $this::ERR_REINSTALL_FAIL_UNLINK
                );
            }
        }

        //If module already exist in "modules" directory
        if ($alreadyCreated) {
            $this->displayMsgNLInCli(
                'Not created. Module already exist in \'modules\' directory.',
                'yellow',
                'bold'
            );
            return;
        }

        //If the creation of the symbolic link has failed.
        if (!symlink($this->sourceSrcPath, $this->targetSrcPath)) {
            $this->displayMsgNLInCli('Symbolic link creation fail.', 'red', 'bold');
            
            throw new Exception(
                'Symbolic link creation fail.',
                $this::ERR_INSTALL_FAIL_SYMLINK
            );
        }

        $this->displayMsgNLInCli('Done', 'green', 'bold');
    }
834306
public function createModule(Module $module)
    {
        $dst = $this->rootDir.'/../src/Terrific/Module/'.StringUtils::camelize($module->getName());

        if($this->toolbarMode === ToolbarListener::DEMO) {
            // prevent module creation in demo mode
            throw new \Exception('This action is not supported in demo mode');
        } else {
            if($this->moduleTemplate) {
                $this->copy($this->moduleTemplate, $dst, $module);
            }

            $this->copy($this->defaultTemplate, $dst, $module);
        }
    }
133271
public function main()
    {
        $map = $this->getMap();

        // Single file symlink
        if (is_string($map)) {
            return $this->symlink($map, $this->getLink());
        }

        // Multiple symlinks
        foreach ($map as $name => $targetPath) {
            $this->symlink($targetPath, $this->getLink() . DIRECTORY_SEPARATOR . $name);
        }

        return true;
    }
72168
public function generate()
    {
        $name = $this->getName();

        if ($this->module->has($name)) {
            if ($this->force) {
                $this->module->delete($name);
            } else {
                $this->console->error("Module [{$name}] already exist!");

                return;
            }
        }

        $this->generateFolders();

        $this->generateFiles();

        if (!$this->plain) {
            $this->generateResources();
        }

        $this->console->info("Module [{$name}] created successfully.");
    }
37903
protected function symlinkProjectFiles(string $projectFilesPath, InputInterface $input, OutputInterface $output): void
    {
        /** @var \DirectoryIterator[] $directories */
        $directories = [];

        $path = $projectFilesPath . '/root_' . $this->environment . '/';
        if ($this->fileSystem->exists($path) && is_dir($path)) {
            $directories[] = new DirectoryIterator($path);
        }

        $path = $projectFilesPath . '/root/';
        if ($this->fileSystem->exists($path) && is_dir($path)) {
            $directories[] = new DirectoryIterator($path);
        }

        foreach ($directories as $directory) {
            foreach ($directory as $item) {
                if ($item->isDot() || $item->isLink()) {
                    continue;
                }

                if ($item->isDir() || $item->isFile()) {
                    if (in_array($item->getBasename(), self::$blacklistedItems, true)) {
                        continue;
                    }

                    $webFolderName = $input->getOption('web-folder');
                    $webFolderName = !empty($webFolderName) ? $webFolderName : 'web';

                    $destination = $this->getContainer()->getParameter('kernel.project_dir') . '/' . $webFolderName . '/' . $item->getBasename();

                    if (!$this->fileSystem->exists(dirname($destination))) {
                        $output->writeln('Skipped creating the symlink for <comment>' . basename($destination) . '</comment> in <comment>' . dirname($destination) . '/</comment>. Folder does not exist!');

                        continue;
                    }

                    if ($item->isDir()) {
                        $this->verifyAndSymlinkDirectory(
                            $item->getPathname(),
                            $destination,
                            $output
                        );
                    } else {
                        $this->verifyAndSymlinkFile(
                            $item->getPathname(),
                            $destination,
                            $output
                        );
                    }
                }
            }
        }
    }
333147
def _make_symlink(self, link_name: str, link_target: str):
        ''''''
        path = self._file_writer_session.extra_resource_path('dummy')

        if path:
            dir_path = os.path.dirname(path)
            symlink_path = os.path.join(dir_path, link_name)

            _logger.debug('symlink {} -> {}', symlink_path, link_target)

            os.symlink(link_target, symlink_path)

            _logger.info(
                _('Created symbolic link {symlink_path} to target {symlink_target}.'),
                symlink_path=symlink_path,
                symlink_target=link_target
            )
462164
protected function symlink($target, $link)
    {
        $fs = FileSystem::getFileSystem();

        if ($this->isRelative()) {
            $link = (new PhingFile($link))->getAbsolutePath();
            $target = rtrim($this->makePathRelative($target, dirname($link)), '/');
        }

        if (is_link($link) && @readlink($link) == $target) {
            $this->log('Link exists: ' . $link, Project::MSG_INFO);

            return true;
        }

        if (file_exists($link) || is_link($link)) {
            if (!$this->getOverwrite()) {
                $this->log('Not overwriting existing link ' . $link, Project::MSG_ERR);

                return false;
            }

            if (is_link($link) || is_file($link)) {
                $fs->unlink($link);
                $this->log('Link removed: ' . $link, Project::MSG_INFO);
            } else {
                $fs->rmdir($link, true);
                $this->log('Directory removed: ' . $link, Project::MSG_INFO);
            }
        }

        $this->log('Linking: ' . $target . ' to ' . $link, Project::MSG_INFO);

        return $fs->symlink($target, $link);
    }
924954
public function init()
    {
        Profiler::start('moduleManager', 'init');
        $module = $this->load($this->directory, array(), true);
        if ($module) {
            $this->mainModule = $module;
            $this->add($module);
//            Profiler::start('moduleManager Init');
            $this->mainModule->init();
            $this->mainModule->register_events();
            if (isset($this->config['modules'])) {
                $this->loadConfig($this->config, $this->mainModule);
            }

            foreach ($this->modules as $module) {
                    $module->init();
                    $module->register_router($this->router);
            }
            foreach ($this->modules as $module) {
                if ($module !== $this->mainModule) {
                    $module->register_events();
                }
            }
//            dump($this->modules);
//            die();
//            Profiler::stop('moduleManager Init');
        } else {
            $file = $this->directory . "/config.yml";
            throw new \Exception('Can\'t not load the main module! Looking for: \'' . $file . '\'. folder 
            realpath: ' . realpath($this->directory));
        }
        Profiler::stop('moduleManager');
    }
362023
public static function installProjectSymlinks(Event $event): void
    {
        $options = self::getOptions($event);
        $consoleDir = static::getConsoleDir($event, 'install project symlinks');

        static::executeCommand($event, $consoleDir, 'ngsite:symlink:project', $options['process-timeout']);
    }
17922
public function install(): OperationResult
    {
        $result = new OperationResult();

        $sourcePath = "{$this->packageInstallDir}/.installer/%s/files";
        foreach ($this->projectType->getProjectDirs() as $projectDir) {
            if (is_dir(sprintf($sourcePath, $projectDir))) {
                /** @var \RecursiveDirectoryIterator $iterator */
                $iterator = new \RecursiveIteratorIterator(
                    new \RecursiveDirectoryIterator(
                        sprintf($sourcePath, $projectDir),
                        \RecursiveDirectoryIterator::SKIP_DOTS
                    ),
                    \RecursiveIteratorIterator::SELF_FIRST
                );

                /** @var \SplFileInfo $file */
                foreach ($iterator as $file) {
                    $target = "{$this->projectRootDir}/{$iterator->getSubPathname()}";
                    if ($file->isDir()) {
                        if (!is_dir($target)) {
                            if (!mkdir($target)) {
                                $result->addErrorMessage("<error>Could not create target directory '${target}'</error>");
                            }
                        }
                    } elseif (!file_exists($target)) {
                        assert(is_string($file->getRealPath()));
                        if (!copy($file->getRealPath(), $target)) {
                            $result->addErrorMessage("<error>Could not copy file to '${target}'</error>");
                        }
                    }
                }
            }
        }

        if (!$result->isFailure()) {
            $result->addStatusMessage("Successfully copied files from package {$this->packageName}");
        }

        return $result;
    }
556126
protected function symlinkPublicDirectory()
    {
        if (! file_exists(public_path('themes/'.$this->getCurrent()))) {
            if (! file_exists(public_path('themes'))) {
                app()->make('files')->makeDirectory(public_path('themes'));
            }

            app()->make('files')->link(
                $this->path('public'), public_path('themes/'.$this->getCurrent())
            );
        }
    }
833494
protected function copyModule(): void
    {
        foreach (self::DIRECTORIES as $directory) {
            $this->copy(
                $this->packagePath . DS . $directory . DS,
                PATH_ROOT . DS . $directory . DS
            );
        }

        $this->installer->getIo()->write(
            sprintf(
                '  - Copied <comment>%s</comment> module to application',
                basename($this->packagePath)
            ),
            true
        );
    }
545911
public function createPhar()
    {

        // run the build process
        $this->build();

        // prepare the PHAR archive name
        $archiveName = sprintf(
            '%s/%s.phar',
            $this->properties['target.dir'],
            $this->properties['webapp.name']
        );

        // prepare the target directory
        $targetDir = $this->properties['target.dir'] . DIRECTORY_SEPARATOR . $this->properties['webapp.version'];

        // copy the composer.json file
        $this->taskFilesystemStack()
             ->copy(
                  __DIR__ . DIRECTORY_SEPARATOR . 'composer.json',
                  $targetDir. DIRECTORY_SEPARATOR. 'composer.json'
             )->run();

          // copy the .semver file
          $this->taskFilesystemStack()
               ->copy(
                   __DIR__ . DIRECTORY_SEPARATOR . '.semver',
                   $targetDir. DIRECTORY_SEPARATOR. '.semver'
               )->run();

          // copy the bootstrap.php file
          $this->taskFilesystemStack()
               ->copy(
                  __DIR__ . DIRECTORY_SEPARATOR . 'bootstrap.php',
                  $targetDir. DIRECTORY_SEPARATOR. 'bootstrap.php'
               )->run();

        // copy the src/etc directory
        $this->taskCopyDir(
                  array(
                      $this->properties['src.dir'] => $targetDir . DIRECTORY_SEPARATOR . 'src'
                  )
               )->run();

        // copy the syfmony directory
        $this->taskCopyDir(
                   array(
                       $this->properties['symfony.dir'] => $targetDir . DIRECTORY_SEPARATOR . 'symfony'
                   )
               )->run();

        // install the composer dependencies
        $this->taskComposerInstall()
            ->dir($targetDir)
            ->noDev()
            ->optimizeAutoloader()
            ->run();

        // prepare the task
        $pharTask = $this->taskPackPhar($archiveName)
            ->compress()
            ->stub('stub.php');

        // load a list with all the source files from the vendor directory
        $finder = Finder::create()->files()
            ->name('*.php')
            ->name('.semver')
            ->name('services.xml')
            ->name('services-1.0.xsd')
            ->name('techdivision-import.json')
            ->in($targetDir)
            ->ignoreDotFiles(false);

        // iterate over the source files of the vendor directory and add them to the PHAR archive
        foreach ($finder as $file) {
            $pharTask->addFile($file->getRelativePathname(), $file->getRealPath());
        }

        // create the PHAR archive
        $pharTask->run();

        // verify PHAR archive is packed correctly
        $this->_exec(sprintf('php %s', $archiveName));

        // prepare the PHAR archive distribution name
        $distArchiveName = sprintf('%s/%s.phar', $this->properties['dist.dir'], $this->properties['webapp.name']);

        // clean up the dist directory
        $this->taskCleanDir($this->properties['dist.dir'])->run();

        // copy the latest PHAR archive to the dist directory
        $this->taskFilesystemStack()->copy($archiveName, $distArchiveName)->run();
    }
702508
public function setupDrupalFilesystem()
    {
        $this->taskFilesystemStack()
            ->chmod($this->sitesPath, 0775, 0000, true)
            ->mkdir("{$this->sitesPath}/default/files", 0775, true)
            ->run();

        if ($this->getProjectVersion() >= 8) {
            $install_path = $this->getInstallPath();

            $this->taskFilesystemStack()
                ->mkdir("{$install_path}/profiles/custom", 0775, true)
                ->mkdir("{$install_path}/modules/custom", 0775, true)
                ->mkdir("{$install_path}/modules/contrib", 0775, true)
                ->run();
        }

        return $this;
    }
1244704
public function create()
	{	
		$blog_dir = getcwd() . '/' . $this->name . '/';
		$this->createBlogDirectory($blog_dir);
		$this->createConfigFile($blog_dir);
		$this->createTemplateFile($blog_dir);
	}
661196
function main() {
    console.log("Will create symlink from " + languageDir + " to " + baseDir);
    let relativeLanguageDir = path.relative(currentDir, languageDir);
    let relativeBaseDir = path.relative(currentDir, baseDir);
    console.log("Using relative paths " + relativeLanguageDir + " to " + relativeBaseDir);
    symlinkOrCopySync(relativeLanguageDir, relativeBaseDir);

    // clean out elm-stuff cache
    glob(path.join(currentDir, "/elm-stuff/**/user/project/*/"+argv.rootModule+"*"), function(er, files) {
        files.forEach(function(file) {
            console.log("clearing out cache at", file);
            fs.removeSync(file);
        });
        if (argv.output) {
            build(argv.output);
        }
    });
}
948461
def CreateLibSymlinks(env, symlinks):
    

    Verbose = False
    for link, linktgt in symlinks:
        linktgt = link.get_dir().rel_path(linktgt)
        link = link.get_path()
        if(Verbose):
            print("CreateLibSymlinks: preparing to add symlink %r -> %r" % (link, linktgt))
        # Delete the (previously created) symlink if exists. Let only symlinks
        # to be deleted to prevent accidental deletion of source files...
        if env.fs.islink(link):
            env.fs.unlink(link)
            if(Verbose):
                print("CreateLibSymlinks: removed old symlink %r" % link)
        # If a file or directory exists with the same name as link, an OSError
        # will be thrown, which should be enough, I think.
        env.fs.symlink(linktgt, link)
        if(Verbose):
            print("CreateLibSymlinks: add symlink %r -> %r" % (link, linktgt))
    return 0