Export modules and check them in. Assumes the log stream already open.
@return exit code of the commit-script.
431031
private int checkInInternal() {

        m_logStream.println("[" + new Date() + "] STARTING Git task");
        m_logStream.println("=========================");
        m_logStream.println();

        if (m_checkout) {
            m_logStream.println("Running checkout script");

        } else if (!(m_resetHead || m_resetRemoteHead)) {
            m_logStream.println("Exporting relevant modules");
            m_logStream.println("--------------------------");
            m_logStream.println();

            exportModules();

            m_logStream.println();
            m_logStream.println("Calling script to check in the exports");
            m_logStream.println("--------------------------------------");
            m_logStream.println();

        } else {

            m_logStream.println();
            m_logStream.println("Calling script to reset the repository");
            m_logStream.println("--------------------------------------");
            m_logStream.println();

        }

        int exitCode = runCommitScript();
        if (exitCode != 0) {
            m_logStream.println();
            m_logStream.println("ERROR: Something went wrong. The script got exitcode " + exitCode + ".");
            m_logStream.println();
        }
        if ((exitCode == 0) && m_checkout) {
            boolean importOk = importModules();
            if (!importOk) {
                return -1;
            }
        }
        m_logStream.println("[" + new Date() + "] FINISHED Git task");
        m_logStream.println();
        m_logStream.close();

        return exitCode;
    }
712228
@Override
    public void actionCommit() {

        if (!hasCommitErrors()) {
            //check if we have to update an existing module or to create a new one
            Set<String> moduleNames = OpenCms.getModuleManager().getModuleNames();
            if (moduleNames.contains(m_module.getName())) {
                // update the module information
                try {
                    OpenCms.getModuleManager().updateModule(getCms(), m_module);
                } catch (CmsException e) {
                    addCommitError(e);
                }
            } else {
                try {
                    m_module = createModuleFolders((CmsModule)m_module.clone());
                    OpenCms.getModuleManager().addModule(getCms(), m_module);
                } catch (CmsException e) {
                    addCommitError(e);
                }
            }
        }

        if (!hasCommitErrors()) {
            // refresh the list
            Map<?, ?> objects = (Map<?, ?>)getSettings().getListObject();
            if (objects != null) {
                objects.remove(CmsModulesList.class.getName());
            }
        }
    }
1241380
@GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/graph/{name}/{version}")
    public Response getModuleGraph(@PathParam("name") final String moduleName,
                                   @PathParam("version") final String moduleVersion,
                                   @Context final UriInfo uriInfo){

        LOG.info("Dependency Checker got a get module graph export request.");

        if(moduleName == null || moduleVersion == null){
            return Response.serverError().status(HttpStatus.NOT_ACCEPTABLE_406).build();
        }

        final FiltersHolder filters = new FiltersHolder();
        filters.init(uriInfo.getQueryParameters());

        final String moduleId = DbModule.generateID(moduleName, moduleVersion);
        final AbstractGraph moduleGraph = getGraphsHandler(filters).getModuleGraph(moduleId);

        return Response.ok(moduleGraph).build();
    }
676039
public Optional<CommitLog> commitAndGetLogs() throws InvalidKBException {
        if (isClosed()) {
            return Optional.empty();
        }
        try {
            return commitWithLogs();
        } finally {
            String closeMessage = ErrorMessage.TX_CLOSED_ON_ACTION.getMessage("committed", keyspace());
            closeTransaction(closeMessage);
        }
    }
665790
def do_finalize(self):
		
		shutit_global.shutit_global_object.yield_to_draw()
		def _finalize(self):
			# Stop all the modules
			self.stop_all()
			# Finalize in reverse order
			self.log('PHASE: finalizing object ' + str(self), level=logging.DEBUG)
			# Login at least once to get the exports.
			for module_id in self.module_ids(rev=True):
				# Only finalize if it's thought to be installed.
				if self.is_installed(self.shutit_map[module_id]):
					self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False)
					if not self.shutit_map[module_id].finalize(self):
						self.fail(module_id + ' failed on finalize', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child) # pragma: no cover
					self.logout(echo=False)
		_finalize(self)
286872
def get_exit_code #:nodoc:
      cmd = options[:override_get_exit_code] || 'echo $?'
      if cmd.respond_to?(:call)
        cmd.call(self)
      else
        debug 'Retrieving exit code from last command...'
        discard_local_buffer do
          send_data cmd + line_ending
          wait_for_prompt 1, 2
          ret = command_output(cmd).strip.to_i
        end
        debug 'Exit code: ' + ret.to_s
        ret
      end
    end
108289
public Set<ModuleModel> getReferencedModules() {
		Set<ModuleModel> set = new HashSet<>();
		set.addAll(exportedModules);
		set.addAll(importedModules);
		return set;
	}
805774
public int getExitCode() {
		int exitCode = 0;
		for (ExitCodeGenerator generator : this.generators) {
			try {
				int value = generator.getExitCode();
				if (value > 0 && value > exitCode || value < 0 && value < exitCode) {
					exitCode = value;
				}
			}
			catch (Exception ex) {
				exitCode = (exitCode != 0) ? exitCode : 1;
				ex.printStackTrace();
			}
		}
		return exitCode;
	}
1014517
function closeStreams(exitCode) {
	// default is 0 if not specified
	exitCode = exitCode === undefined ? 0 : exitCode;

	if (streams.length) {
		streams.forEach(function (logger) {
			logger.write({ level: bunyan.TRACE, msg: util.format('exited with code %d', exitCode) });
			logger.stream.end();
			// jscs:disable jsDoc
			logger.write = function () {};
		});
	}
}
716691
@SuppressWarnings("resource")
    private boolean importModules() {

        boolean result = true;

        try {
            m_logStream.println("Checking module dependencies.");
            Multimap<String, String> dependencies = HashMultimap.create();
            Set<String> unsortedModules = Sets.newHashSet(m_modulesToExport);
            for (String module : m_modulesToExport) {
                String manifestPath = CmsStringUtil.joinPaths(
                    m_currentConfiguration.getModulesPath(),
                    module,
                    m_currentConfiguration.getResourcesSubFolder(),
                    "manifest.xml");
                Document doc = CmsXmlUtils.unmarshalHelper(
                    CmsFileUtil.readFully(new FileInputStream(manifestPath)),
                    new CmsXmlEntityResolver(null));

                List<?> depNodes = doc.getRootElement().selectNodes("//dependencies/dependency/@name");
                for (Object nodeObj : depNodes) {
                    Node node = ((Node)nodeObj);
                    String dependency = node.getText();
                    if (m_modulesToExport.contains(dependency)) {
                        // we can only handle dependencies between selected modules
                        // and just have to assume that other dependencies are fulfilled
                        dependencies.put(module, dependency);
                    }
                }
            }
            List<String> sortedModules = Lists.newArrayList();
            // if there are no cycles, this loop will find one element on each iteration
            for (int i = 0; i < m_modulesToExport.size(); i++) {
                String nextModule = null;
                for (String key : unsortedModules) {
                    if (dependencies.get(key).isEmpty()) {
                        nextModule = key;
                        break;
                    }
                }
                if (nextModule != null) {
                    sortedModules.add(nextModule);
                    unsortedModules.remove(nextModule);
                    for (String key : Sets.newHashSet(dependencies.keySet())) { // copy key set to avoid concurrent modification exception
                        dependencies.get(key).remove(nextModule);
                    }
                }
            }
            m_logStream.println("Modules sorted by dependencies: " + sortedModules);
            for (String moduleName : sortedModules) {
                String dir = CmsStringUtil.joinPaths(
                    m_currentConfiguration.getModulesPath(),
                    moduleName,
                    m_currentConfiguration.getResourcesSubFolder());
                File dirEntry = new File(dir);
                if (!dirEntry.exists()) {
                    continue;
                }
                try {
                    m_logStream.println("Creating temp file for module " + moduleName);
                    File outputFile = File.createTempFile(moduleName + "-", ".zip");
                    FileOutputStream fos = new FileOutputStream(outputFile);
                    m_logStream.println("Zipping module structure to " + outputFile.getAbsolutePath());
                    zipRfsFolder(dirEntry, fos);
                    result &= importModule(outputFile);
                    outputFile.delete();
                } catch (Exception e) {
                    LOG.error(e.getLocalizedMessage(), e);
                    e.printStackTrace(m_logStream);
                    result = false;
                }
            }
        } catch (Exception e) {

            LOG.error(e.getLocalizedMessage(), e);
            m_logStream.println("Unable to check dependencies for modules, giving up.");
            e.printStackTrace(m_logStream);
            result = false;
        }
        return result;
    }
154646
@GwtIncompatible("Unnecessary")
  protected int doRun() throws IOException {
    Compiler.setLoggingLevel(Level.parse(config.loggingLevel));

    compiler = createCompiler();
    B options = createOptions();
    setRunOptions(options);

    List<SourceFile> externs = createExterns(options);
    List<JSModule> modules = null;
    Result result = null;

    rootRelativePathsMap = constructRootRelativePathsMap();

    boolean writeOutputToFile = !config.jsOutputFile.isEmpty();
    List<String> outputFileNames = new ArrayList<>();
    if (writeOutputToFile) {
      outputFileNames.add(config.jsOutputFile);
    }

    boolean createCommonJsModules = false;
    if (options.processCommonJSModules
        && (config.module.size() == 1 && "auto".equals(config.module.get(0)))) {
      createCommonJsModules = true;
      config.module.remove(0);
    }

    List<JsModuleSpec> jsModuleSpecs = new ArrayList<>();
    for (int i = 0; i < config.module.size(); i++) {
      jsModuleSpecs.add(JsModuleSpec.create(config.module.get(i), i == 0));
    }
    List<JsonFileSpec> jsonFiles = null;

    if (config.jsonStreamMode == JsonStreamMode.IN ||
        config.jsonStreamMode == JsonStreamMode.BOTH) {
      jsonFiles = parseJsonFilesFromInputStream();

      ImmutableMap.Builder<String, SourceMapInput> inputSourceMaps
          = new ImmutableMap.Builder<>();
      ImmutableMap.Builder<String, String> inputPathByWebpackId = new ImmutableMap.Builder<>();

      boolean foundJsonInputSourceMap = false;
      for (JsonFileSpec jsonFile : jsonFiles) {
        if (jsonFile.getSourceMap() != null && jsonFile.getSourceMap().length() > 0) {
          String sourceMapPath = jsonFile.getPath() + ".map";
          SourceFile sourceMap = SourceFile.fromCode(sourceMapPath,
              jsonFile.getSourceMap());
          inputSourceMaps.put(jsonFile.getPath(), new SourceMapInput(sourceMap));
          foundJsonInputSourceMap = true;
        }
        if (jsonFile.getWebpackId() != null) {
          inputPathByWebpackId.put(jsonFile.getWebpackId(), jsonFile.getPath());
        }
      }

      if (foundJsonInputSourceMap) {
        inputSourceMaps.putAll(options.inputSourceMaps);
        options.inputSourceMaps = inputSourceMaps.build();
      }

      compiler.initWebpackMap(inputPathByWebpackId.build());
    } else {
      ImmutableMap<String, String> emptyMap = ImmutableMap.of();
      compiler.initWebpackMap(emptyMap);
    }

    compiler.initWarningsGuard(options.getWarningsGuard());

    List<SourceFile> inputs =
        createSourceInputs(jsModuleSpecs, config.mixedJsSources, jsonFiles, config.moduleRoots);
    if (!jsModuleSpecs.isEmpty()) {
      if (isInTestMode()) {
        modules = modulesSupplierForTesting.get();
      } else {
        if (JsonStreamMode.IN.equals(config.jsonStreamMode)
            || JsonStreamMode.NONE.equals(config.jsonStreamMode)) {
          for (JsModuleSpec m : jsModuleSpecs) {
            checkModuleName(m.getName());
          }
        }
        modules = createJsModules(jsModuleSpecs, inputs);
      }
      for (JSModule m : modules) {
        outputFileNames.add(getModuleOutputFileName(m));
      }

      compiler.initModules(externs, modules, options);
    } else {
      compiler.init(externs, inputs, options);
    }

    if (options.printConfig) {
      compiler.printConfig(System.err);
    }


    String saveAfterChecksFilename = config.getSaveAfterChecksFileName();
    String continueSavedCompilationFilename = config.getContinueSavedCompilationFileName();
    if (config.skipNormalOutputs) {
      // TODO(bradfordcsmith): Should we be ignoring possible init/initModules() errors here?
      compiler.orderInputsWithLargeStack();
    } else if (compiler.hasErrors()) {
      // init() or initModules() encountered an error.
      compiler.generateReport();
      result = compiler.getResult();
    } else if (options.getInstrumentForCoverageOnly()) {
      result = instrumentForCoverage();
    } else if (saveAfterChecksFilename != null) {
      result = performStage1andSave(saveAfterChecksFilename);
    } else if (continueSavedCompilationFilename != null) {
      result = restoreAndPerformStage2(continueSavedCompilationFilename);
      if (modules != null) {
        modules = ImmutableList.copyOf(compiler.getModules());
      }
    } else {
      result = performFullCompilation();
    }

    if (createCommonJsModules) {
      // For CommonJS modules construct modules from actual inputs.
      modules = ImmutableList.copyOf(compiler.getModules());
      for (JSModule m : modules) {
        outputFileNames.add(getModuleOutputFileName(m));
      }
    }

    for (String outputFileName : outputFileNames) {
      if (compiler.getSourceFileByName(outputFileName) != null) {
        compiler.report(
            JSError.make(OUTPUT_SAME_AS_INPUT_ERROR, outputFileName));
        return 1;
      }
    }

    return processResults(result, modules, options);
  }
293568
private Exit exit(final Exit exit) {
        final long start = System.currentTimeMillis();
        final long max = this.options.lifetime();
        return new Exit.Or(
            exit,
            new Lifetime(start, max)
        );
    }
142972
private synchronized void initModuleExportPoints() {

        Set<CmsExportPoint> exportPoints = new HashSet<CmsExportPoint>();
        Iterator<CmsModule> i = m_modules.values().iterator();
        while (i.hasNext()) {
            CmsModule module = i.next();
            List<CmsExportPoint> moduleExportPoints = module.getExportPoints();
            for (int j = 0; j < moduleExportPoints.size(); j++) {
                CmsExportPoint point = moduleExportPoints.get(j);
                if (exportPoints.contains(point)) {
                    if (LOG.isWarnEnabled()) {
                        LOG.warn(
                            Messages.get().getBundle().key(
                                Messages.LOG_DUPLICATE_EXPORT_POINT_2,
                                point,
                                module.getName()));
                    }
                } else {
                    exportPoints.add(point);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(
                            Messages.get().getBundle().key(Messages.LOG_ADD_EXPORT_POINT_2, point, module.getName()));
                    }
                }
            }
        }
        m_moduleExportPoints = Collections.unmodifiableSet(exportPoints);
    }
1172128
protected String exportModuleScriptTag(String moduleName) {

        String result = "<meta name=\""
            + CmsCoreData.META_PARAM_MODULE_KEY
            + "\" content=\""
            + moduleName
            + "\" >\n<script type=\"text/javascript\" src=\""
            + CmsWorkplace.getStaticResourceUri("gwt/opencms/opencms.nocache.js");
        result += "\"></script>\n";
        return result;
    }
957985
public void exportModule(String moduleName) throws Exception {

        CmsModule module = OpenCms.getModuleManager().getModule(moduleName);

        if (module == null) {
            throw new CmsDbEntryNotFoundException(Messages.get().container(Messages.ERR_UNKNOWN_MODULE_1, moduleName));
        }

        String filename = OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(
            OpenCms.getSystemInfo().getPackagesRfsPath()
                + CmsSystemInfo.FOLDER_MODULES
                + moduleName
                + "_"
                + OpenCms.getModuleManager().getModule(moduleName).getVersion().toString());

        List<String> moduleResources = CmsModule.calculateModuleResourceNames(m_cms, module);
        String[] resources = new String[moduleResources.size()];
        System.arraycopy(moduleResources.toArray(), 0, resources, 0, resources.length);

        // generate a module export handler
        CmsModuleImportExportHandler moduleExportHandler = new CmsModuleImportExportHandler();
        moduleExportHandler.setFileName(filename);
        moduleExportHandler.setAdditionalResources(resources);
        moduleExportHandler.setModuleName(module.getName().replace('\\', '/'));
        moduleExportHandler.setDescription(
            getMessages().key(
                Messages.GUI_SHELL_IMPORTEXPORT_MODULE_HANDLER_NAME_1,
                new Object[] {moduleExportHandler.getModuleName()}));

        // export the module
        OpenCms.getImportExportManager().exportData(
            m_cms,
            moduleExportHandler,
            new CmsShellReport(m_cms.getRequestContext().getLocale()));
    }
827149
def finish(build_script_lines)
      # keep track of changed files
      start_id = @git.latest_id("tetra: dry-run-started")
      changed_files = @git.changed_files("src", start_id)

      # revert to pre-dry-run status
      @git.revert_directories(["src"], start_id)

      # prepare commit comments
      comments = ["Dry run finished\n", "tetra: dry-run-finished"]
      comments += changed_files.map { |f| "tetra: file-changed: #{f}" }
      comments += build_script_lines.map { |l| "tetra: build-script-line: #{l}" }

      # commit end of dry run
      @git.commit_directories(["kit"], comments.join("\n"))
    end
212686
protected List<String> getModulesToDelete() {

        List<String> result = new ArrayList<String>();
        for (int i = 0; i < OBSOLETE_MODULES.length; i++) {
            if (OpenCms.getModuleManager().hasModule(OBSOLETE_MODULES[i])) {
                result.add(OBSOLETE_MODULES[i]);
            }
        }
        return result;
    }