001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.maven.enforcer.rules; 020 021import javax.inject.Inject; 022import javax.inject.Named; 023 024import java.util.Objects; 025import java.util.Optional; 026 027import org.apache.maven.artifact.Artifact; 028import org.apache.maven.enforcer.rule.api.EnforcerRuleException; 029import org.apache.maven.project.MavenProject; 030 031/** 032 * This rule checks that the current project is not a release. 033 */ 034@Named("requireSnapshotVersion") 035public final class RequireSnapshotVersion extends AbstractStandardEnforcerRule { 036 037 /** 038 * Allows this rule to fail when the parent is defined as a release. 039 */ 040 private boolean failWhenParentIsRelease = true; 041 042 private final MavenProject project; 043 044 @Inject 045 public RequireSnapshotVersion(MavenProject project) { 046 this.project = Objects.requireNonNull(project); 047 } 048 049 @Override 050 public void execute() throws EnforcerRuleException { 051 052 Artifact artifact = project.getArtifact(); 053 054 if (!artifact.isSnapshot()) { 055 String message = getMessage(); 056 StringBuilder sb = new StringBuilder(); 057 if (message != null) { 058 sb.append(message).append(System.lineSeparator()); 059 } 060 sb.append("This project cannot be a release:").append(artifact.getId()); 061 throw new EnforcerRuleException(sb.toString()); 062 } 063 if (failWhenParentIsRelease && project.hasParent()) { 064 Artifact parentArtifact = Optional.ofNullable(project.getParent()) 065 .map(MavenProject::getArtifact) 066 .orElse(null); 067 if (parentArtifact != null && !parentArtifact.isSnapshot()) { 068 throw new EnforcerRuleException("Parent cannot be a release: " + parentArtifact.getId()); 069 } 070 } 071 } 072 073 public void setFailWhenParentIsRelease(boolean failWhenParentIsRelease) { 074 this.failWhenParentIsRelease = failWhenParentIsRelease; 075 } 076 077 @Override 078 public String toString() { 079 return String.format( 080 "RequireSnapshotVersion[message=%s, failWhenParentIsRelease=%b]", 081 getMessage(), failWhenParentIsRelease); 082 } 083}