Beispiel #1
0
 /**
  * Resolves a logical environment name for a project, such as <code>Testing</code> to the physical
  * projcect/team specific namespace value.
  *
  * <p>It tries to find a fabric8.yml file in this folder or a parent folder and loads it and tries
  * to use it to find the namespace for the given environment or uses environment variables to
  * resolve the environment name -> physical namespace
  *
  * @return the namespace
  */
 private static String findNamespaceForEnvironment(String environment, Map<String, String> map) {
   String namespace = null;
   if (!Strings.isNullOrBlank(environment)) {
     String basedir = System.getProperty("basedir", ".");
     File folder = new File(basedir);
     ProjectConfig projectConfig = ProjectConfigs.findFromFolder(folder);
     if (projectConfig != null) {
       LinkedHashMap<String, String> environments = projectConfig.getEnvironments();
       if (environments != null) {
         namespace = environments.get(environment);
       }
     }
     String key = environment.toLowerCase() + ".namespace";
     if (Strings.isNullOrBlank(namespace)) {
       // lets try find an environment variable or system property
       namespace = getStringProperty(key, map, null);
     }
     if (Strings.isNullOrBlank(namespace)) {
       throw new IllegalStateException(
           "A fabric8 environment '"
               + environment
               + "' has been specified, but no matching namespace was found in the fabric8.yml file or '"
               + key
               + "' system property");
     }
   }
   return namespace;
 }
  @Override
  public Result execute(UIExecutionContext context) throws Exception {
    LOG.info("Creating the fabric8.yml file");

    String fileName = ProjectConfigs.FILE_NAME;
    Project project = getSelectedProject(context);
    File configFile = getProjectConfigFile(context.getUIContext(), getSelectedProject(context));
    if (configFile == null) {
      // lets not fail as we typically want to execute SaveDevOpsStep next...
      return Results.success();
    }
    ProjectConfig config = null;
    boolean hasFile = false;
    if (configFile.exists()) {
      config = ProjectConfigs.parseProjectConfig(configFile);
      hasFile = true;
    }
    if (config == null) {
      config = new ProjectConfig();
    }

    CommandHelpers.putComponentValuesInAttributeMap(context, inputComponents);
    updateConfiguration(context, config);
    LOG.info("Result: " + config);

    String message;
    if (config.isEmpty() && !hasFile) {
      message = "No " + fileName + " need be generated as there is no configuration";
      return Results.success(message);
    } else {
      String operation = "Updated";
      if (!configFile.exists()) {
        operation = "Created";
      }
      ProjectConfigs.saveConfig(config, configFile);
      message = operation + " " + fileName;
    }

    // now lets update the devops stuff
    UIContext uiContext = context.getUIContext();
    Map<Object, Object> attributeMap = uiContext.getAttributeMap();

    String gitUrl = getStringAttribute(attributeMap, "gitUrl");
    if (Strings.isNullOrBlank(gitUrl)) {
      gitUrl = getStringAttribute(attributeMap, "gitAddress");
    }

    Object object = attributeMap.get(Project.class);
    String user = getStringAttribute(attributeMap, "gitUser");
    String named = getStringAttribute(attributeMap, "projectName");
    ;
    File basedir = CommandHelpers.getBaseDir(project);
    if (basedir == null && configFile != null) {
      basedir = configFile.getParentFile();
    }

    if (object instanceof Project) {
      Project newProject = (Project) object;
      MetadataFacet facet = newProject.getFacet(MetadataFacet.class);
      if (facet != null) {
        if (Strings.isNullOrBlank(named)) {
          named = facet.getProjectName();
        }
        if (Strings.isNullOrBlank(gitUrl)) {
          String address = getStringAttribute(attributeMap, "gitAddress");
          gitUrl = address + user + "/" + named + ".git";
        }
      } else {
        LOG.error("No MetadataFacet for newly created project " + newProject);
      }
    } else {
      // updating an existing project - so lets try find the git url from the current source code
      if (Strings.isNullOrBlank(gitUrl)) {
        gitUrl = GitHelpers.extractGitUrl(basedir);
      }
      if (basedir != null) {
        if (Strings.isNullOrBlank(named)) {
          named = basedir.getName();
        }
      }
    }
    // lets default the environments from the pipeline
    PipelineDTO pipelineValue = pipeline.getValue();
    LOG.info("Using pipeline " + pipelineValue);
    String buildName = config.getBuildName();
    if (Strings.isNotBlank(buildName)) {
      if (pipelineValue != null) {
        List<String> environments = pipelineValue.getEnvironments();
        if (environments == null) {
          environments = new ArrayList<>();
        }
        LinkedHashMap<String, String> environmentMap = new LinkedHashMap<>();
        if (environments.isEmpty()) {
          environmentMap.put("Current", namespace);
        } else {
          for (String environment : environments) {
            String envNamespace = namespace + "-" + environment.toLowerCase();
            environmentMap.put(environment, envNamespace);
          }
        }
        config.setEnvironments(environmentMap);
      }
    }
    LOG.info("Configured project " + buildName + " environments: " + config.getEnvironments());
    ProjectConfigs.defaultEnvironments(config, namespace);

    String projectName = config.getBuildName();
    if (Strings.isNullOrBlank(projectName)) {
      projectName = named;
      config.setBuildName(projectName);
    }

    LOG.info("Project name is: " + projectName);
    if (Strings.isNotBlank(projectName) && project != null) {
      MavenFacet maven = project.getFacet(MavenFacet.class);
      Model pom = maven.getModel();
      if (pom != null
          && !isFunktionParentPom(project)
          && !isFabric8MavenPlugin3OrGreater(project)) {
        Properties properties = pom.getProperties();
        boolean updated = false;
        updated =
            MavenHelpers.updatePomProperty(
                properties, "fabric8.label.project", projectName, updated);
        updated =
            MavenHelpers.updatePomProperty(
                properties, "fabric8.label.version", "${project.version}", updated);
        if (updated) {
          LOG.info("Updating pom.xml properties!");
          maven.setModel(pom);
        } else {
          LOG.warn("Did not update pom.xml properties!");
        }
      } else {
        LOG.warn("No pom.xml found!");
      }
    }

    Boolean copyFlowToProjectValue = copyPipelineToProject.getValue();
    if (copyFlowToProjectValue != null && copyFlowToProjectValue.booleanValue()) {
      if (basedir == null || !basedir.isDirectory()) {
        LOG.warn("Cannot copy the pipeline to the project as no basedir!");
      } else {
        String flow = null;
        PipelineDTO pipelineDTO = pipelineValue;
        if (pipelineDTO != null) {
          flow = pipelineDTO.getValue();
        }
        if (Strings.isNullOrBlank(flow)) {
          LOG.warn("Cannot copy the pipeline to the project as no pipeline selected!");
        } else {
          String flowText = getFlowContent(flow, uiContext);
          if (Strings.isNullOrBlank(flowText)) {
            LOG.warn(
                "Cannot copy the pipeline to the project as no pipeline text could be loaded!");
          } else {
            flowText = Strings.replaceAllWithoutRegex(flowText, "GIT_URL", "'" + gitUrl + "'");
            File newFile = new File(basedir, ProjectConfigs.LOCAL_FLOW_FILE_NAME);
            Files.writeToFile(newFile, flowText.getBytes());
            LOG.info("Written pipeline to " + newFile);
            if (config != null) {
              config.setPipeline(null);
              config.setUseLocalFlow(true);
            }
          }
        }
      }
    }

    final DevOpsConnector connector = new DevOpsConnector();
    connector.setProjectConfig(config);
    connector.setTryLoadConfigFileFromRemoteGit(false);
    connector.setUsername(user);
    connector.setPassword(getStringAttribute(attributeMap, "gitPassword"));
    connector.setBranch(getStringAttribute(attributeMap, "gitBranch", "master"));
    connector.setBasedir(basedir);
    connector.setGitUrl(gitUrl);
    connector.setRepoName(named);

    connector.setRegisterWebHooks(true);

    // lets not trigger the jenkins webhook yet as the git push should trigger the build
    connector.setTriggerJenkinsJob(false);

    LOG.info("Using connector: " + connector);

    /*
            attributeMap.put("registerWebHooks", new Runnable() {
                @Override
                public void run() {
                    LOG.info("Now registering webhooks!");
                    connector.registerWebHooks();
                }
            });
    */
    try {
      connector.execute();
    } catch (Exception e) {
      LOG.error("Failed to update DevOps resources: " + e, e);
    }

    return Results.success(message);
  }
  @Override
  public void initializeUI(UIBuilder builder) throws Exception {
    final UIContext context = builder.getUIContext();
    copyPipelineToProject.setValue(Boolean.TRUE);
    pipeline.setCompleter(
        new UICompleter<PipelineDTO>() {
          @Override
          public Iterable<PipelineDTO> getCompletionProposals(
              UIContext context, InputComponent<?, PipelineDTO> input, String value) {
            return getPipelines(context, true);
          }
        });
    pipeline.setValueConverter(
        new Converter<String, PipelineDTO>() {
          @Override
          public PipelineDTO convert(String text) {
            return getPipelineForValue(context, text);
          }
        });
    pipeline.addValueChangeListener(
        new ValueChangeListener() {
          @Override
          public void valueChanged(ValueChangeEvent event) {
            String value = event.getNewValue() != null ? event.getNewValue().toString() : null;
            if (value != null) {
              String description = getDescriptionForFlow(value);
              pipeline.setNote(description != null ? description : "");
            } else {
              pipeline.setNote("");
            }
            boolean canCopy = Strings.isNotBlank(value);
            copyPipelineToProject.setEnabled(canCopy);
          }
        });
    if (getCurrentSelectedProject(context) != null) {
      PipelineDTO defaultValue = getPipelineForValue(context, DEFAULT_MAVEN_FLOW);
      if (defaultValue != null) {
        pipeline.setDefaultValue(defaultValue);
        pipeline.setValue(defaultValue);
      }
    }
    chatRoom.setCompleter(
        new UICompleter<String>() {
          @Override
          public Iterable<String> getCompletionProposals(
              UIContext context, InputComponent<?, String> input, String value) {
            return filterCompletions(getChatRoomNames(), value);
          }
        });
    chatRoom.addValueChangeListener(
        new ValueChangeListener() {
          @Override
          public void valueChanged(ValueChangeEvent event) {
            String value = event.getNewValue() != null ? event.getNewValue().toString() : null;
            if (value != null) {
              String description = getDescriptionForChatRoom(value);
              chatRoom.setNote(description != null ? description : "");
            } else {
              chatRoom.setNote("");
            }
          }
        });
    issueProjectName.setCompleter(
        new UICompleter<String>() {
          @Override
          public Iterable<String> getCompletionProposals(
              UIContext context, InputComponent<?, String> input, String value) {
            return filterCompletions(getIssueProjectNames(), value);
          }
        });
    issueProjectName.addValueChangeListener(
        new ValueChangeListener() {
          @Override
          public void valueChanged(ValueChangeEvent event) {
            String value = event.getNewValue() != null ? event.getNewValue().toString() : null;
            if (value != null) {
              String description = getDescriptionForIssueProject(value);
              issueProjectName.setNote(description != null ? description : "");
            } else {
              issueProjectName.setNote("");
            }
          }
        });

    // lets initialise the data from the current config if it exists
    ProjectConfig config = null;
    Project project = getCurrentSelectedProject(context);
    File configFile = getProjectConfigFile(context, getSelectedProject(context));
    if (configFile != null && configFile.exists()) {
      config = ProjectConfigs.parseProjectConfig(configFile);
    }
    if (config != null) {
      PipelineDTO flow = getPipelineForValue(context, config.getPipeline());
      if (flow != null) {
        CommandHelpers.setInitialComponentValue(this.pipeline, flow);
      }
      CommandHelpers.setInitialComponentValue(chatRoom, config.getChatRoom());
      CommandHelpers.setInitialComponentValue(issueProjectName, config.getIssueProjectName());
      CommandHelpers.setInitialComponentValue(codeReview, config.getCodeReview());
    }
    inputComponents = new ArrayList<>();
    File jenkinsFile = CommandHelpers.getProjectContextFile(context, project, "Jenkinsfile");
    boolean hasJenkinsFile = Files.isFile(jenkinsFile);
    LOG.debug("Has Jenkinsfile " + hasJenkinsFile + " with file: " + jenkinsFile);
    if (!hasJenkinsFile) {
      inputComponents.addAll(
          CommandHelpers.addInputComponents(builder, pipeline, copyPipelineToProject));
    }
    inputComponents.addAll(
        CommandHelpers.addInputComponents(builder, chatRoom, issueProjectName, codeReview));
  }