Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.codehaus.mojo.rpm;
  
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
  * with the License.  You may obtain a copy of the License at
  *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  */
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 
Utility to write spec file based on AbstractRPMMojo instance.

Author(s):
Brett Okken
Since:
2.0
 
 final class SpecWriter
 {
     private final AbstractRPMMojo mojo;
 
     private final PrintWriter spec;

    
Creates instance with the mojo to use and the spec to write to.

Parameters:
mojo The mojo with the attributes to generate a spec file for.
spec The target to write the spec file to.
 
     public SpecWriterAbstractRPMMojo mojoPrintWriter spec )
     {
         super();
         this. = mojo;
         this. = spec;
     }

    
Writes the spec file to spec using the attributes of mojo.

 
     public void writeSpecFile()
         throws MojoExecutionExceptionIOException
     {
         writeList.getDefineStatements(), "%define " );
 
         .println"Name: " + .getName() );
         .println"Version: " + .getVersion() );
         .println"Release: " + .getRelease() );
 
         writeNonNullDirective"Summary".getSummary() );
         writeNonNullDirective"License".getLicense() );
         writeNonNullDirective"Distribution".getDistribution() );
 
         if ( .getIcon() != null )
         {
             .println"Icon: " + .getIcon().getName() );
         }
 
         writeNonNullDirective"Vendor".getVendor() );
         writeNonNullDirective"URL".getUrl() );
         writeNonNullDirective"Group".getGroup() );
         writeNonNullDirective"Packager".getPackager() );
 
         writeList.getProvides(), "Provides: " );
         writeList.getRequires(), "Requires: " );
         writeList.getPrereqs(), "PreReq: " );
         writeList.getObsoletes(), "Obsoletes: " );
         writeList.getConflicts(), "Conflicts: " );
 
         .println"autoprov: " + ( .isAutoProvides() ? "yes" : "no" ) );
         .println"autoreq: " + ( .isAutoRequires() ? "yes" : "no" ) );
 
         if ( .getPrefixes() != null )
         {
             for ( String prefix.getPrefixes() )
             {
                .println"Prefix: " + prefix );
            }
        }
        if ( "noarch".equals.getTargetArch() ) )
        {
            .println"BuildArch: " + .getTargetArch() );
        }
        .println"BuildRoot: " + FileHelper.toUnixPath.getRPMBuildroot() ) );
        .println();
        .println"%description" );
        if ( .getDescription() != null )
        {
            .println.getDescription() );
        }
        if ( !.getMappings().isEmpty() )
        {
            writeMove();
        }
        writeLinks();
        if ( .getInstallScriptlet() != null )
        {
            .println();
            .getInstallScriptlet().writeContent );
        }
        writeFiles();
        writeScripts();
        if ( .getTriggers() != null )
        {
            for ( BaseTrigger trigger : .getTriggers() )
            {
                trigger.writeTrigger );
            }
        }
        if ( .getChangelog() != null )
        {
            .println();
            .println"%changelog" );
            .println.getChangelog() );
        }
    }

    
Writes the %files directive based on AbstractRPMMojo.
    private void writeFiles()
    {
        final Log log = .getLog();
        .println();
        .println"%files" );
        .printlngetDefAttrString() );
        for ( Mapping map : .getMappings() )
        {
            // For each mapping we need to determine which files in the destination were defined by this
            // mapping so that we can write the %attr statement correctly.
            final String destination = map.getDestination();
            final File absoluteDestination = map.getAbsoluteDestination();
            final String attrString =
                map.getAttrString.getDefaultFilemode(), .getDefaultGroupname(), .getDefaultUsername() );
            final String baseFileString = attrString + "  \"" + destination + .;
            if ( map.hasSoftLinks() && !absoluteDestination.exists() )
            {
                // @TODO will this ever happen since absoluteDestination.exists() always likely true
                log.debug"writing attribute string for directory created by soft link: " + destination );
                .printlnattrString + " \"" + destination + "\"" );
                continue;
            }
            final List<Stringincludes = map.getCopiedFileNamesRelativeToDestination();
            final List<Stringlinks = map.getLinkedFileNamesRelativeToDestination();
            if ( map.isSoftLinkOnly() )
            {
                // map has only soft links, no need to do the scan (MRPM-173)
                log.debug"writing attribute string for softlink only source" );
                for ( String link : links )
                {
                    .printbaseFileString );
                    .printlnlink + "\"" );
                }
                continue;
            }
            final DirectoryScanner scanner = new DirectoryScanner();
            scanner.setBasedirabsoluteDestination );
            // the linked files are not present yet (will be "installed" during rpm build)
            // so they cannot be "included"
            scanner.setIncludesincludes.isEmpty() ? null : includes.toArraynew String[includes.size()] ) );
            scanner.setExcludesnull );
            scanner.scan();
            if ( scanner.isEverythingIncluded() && links.isEmpty() && map.isDirectoryIncluded()
                && !map.isRecurseDirectories() )
            {
                log.debug"writing attribute string for directory: " + destination );
                .printlnattrString + " \"" + destination + "\"" );
            }
            else
            {
                log.debug"writing attribute string for identified files in directory: " + destination );
                // only list files if requested (directoryIncluded == false) or we have to
                if ( !( map.isDirectoryIncluded() && scanner.isEverythingIncluded() && links.isEmpty() ) )
                {
                    final String[] files = scanner.getIncludedFiles();
                    for ( String file : files )
                    {
                        .printbaseFileString );
                        .printlnfile + "\"" );
                    }
                }
                if ( map.isRecurseDirectories() )
                {
                    final String[] dirs = scanner.getIncludedDirectories();
                    if ( map.isDirectoryIncluded() )
                    {
                        // write out destination first
                        .printlnbaseFileString + "\"" );
                    }
                    for ( String dir : dirs )
                    {
                        // do not write out base file (destination) again
                        if ( dir.length() > 0 )
                        {
                            .printbaseFileString );
                            .printlndir + "\"" );
                        }
                    }
                }
                // since the linked files are not present in directory (yet), the scanner will not find them
                for ( String link : links )
                {
                    .printbaseFileString );
                    .printlnlink + "\"" );
                }
            }
        }
    }

    
Writes the beginning of the %install which includes moving all files from the AbstractRPMMojo.getBuildroot() to AbstractRPMMojo.getRPMBuildroot().
    private void writeMove()
    {
        final String tmpBuildRoot = FileHelper.toUnixPath.getBuildroot() );
        .println();
        .println"%install" );
        .println();
        .println"if [ -d $RPM_BUILD_ROOT ];" );
        .println"then" );
        .print"  mv " );
        .printtmpBuildRoot );
        .println"/* $RPM_BUILD_ROOT" );
        .println"else" );
        .print"  mv " );
        .printtmpBuildRoot );
        .println" $RPM_BUILD_ROOT" );
        .println"fi" );
        // MRPM-168
        .println"chmod -R +w $RPM_BUILD_ROOT" );
    }

    
Writes the install commands to link files.
    private void writeLinks()
    {
        if ( !.getLinkTargetToSources().isEmpty() )
        {
            .println();
            for ( Map.Entry<StringList<SoftlinkSource>> directoryToSourcesEntry : .getLinkTargetToSources().entrySet() )
            {
                String directory = directoryToSourcesEntry.getKey();
                if ( directory.startsWith"/" ) )
                {
                    directory = directory.substring( 1 );
                }
                if ( directory.endsWith"/" ) )
                {
                    directory = directory.substring( 0, directory.length() - 1 );
                }
                final List<SoftlinkSourcesources = directoryToSourcesEntry.getValue();
                final int sourceCnt = sources.size();
                if ( sourceCnt == 1 )
                {
                    final SoftlinkSource linkSource = sources.get( 0 );
                    final String macroEvaluatedLocation = linkSource.getMacroEvaluatedLocation();
                    final File buildSourceLocation;
                    if ( macroEvaluatedLocation.startsWith"/" ) )
                    {
                        buildSourceLocation = new File.getBuildroot(), macroEvaluatedLocation );
                    }
                    else
                    {
                        buildSourceLocation = new File.getBuildroot(), directory + '/' + macroEvaluatedLocation );
                    }
                    if ( buildSourceLocation.isDirectory() )
                    {
                        final DirectoryScanner scanner = scanLinkSourcelinkSourcebuildSourceLocation );
                        if ( scanner.isEverythingIncluded() )
                        {
                            final File destinationFile = linkSource.getSourceMapping().getAbsoluteDestination();
                            destinationFile.delete();
                            .print"ln -s " );
                            .printlinkSource.getLocation() );
                            .print" $RPM_BUILD_ROOT/" );
                            .printdirectory );
                            final String dest = linkSource.getDestination();
                            if ( dest != null )
                            {
                                .print'/' );
                                .printdest );
                                linkSource.getSourceMapping().addLinkedFileNameRelativeToDestinationdest );
                            }
                            .println();
                        }
                        else
                        {
                            linkScannedFilesdirectorylinkSourcescanner );
                        }
                    }
                    else
                    {
                        linkSingleFiledirectorylinkSource );
                    }
                }
                else
                {
                    for ( SoftlinkSource linkSource : sources )
                    {
                        final String sourceLocation = linkSource.getMacroEvaluatedLocation();
                        final File buildSourceLocation;
                        if ( sourceLocation.startsWith"/" ) )
                        {
                            buildSourceLocation = new File.getBuildroot(), sourceLocation );
                        }
                        else
                        {
                            buildSourceLocation = new File.getBuildroot(), directory + '/' + sourceLocation );
                        }
                        if ( buildSourceLocation.isDirectory() )
                        {
                            final DirectoryScanner scanner = scanLinkSourcelinkSourcebuildSourceLocation );
                            linkScannedFilesdirectorylinkSourcescanner );
                        }
                        else
                        {
                            linkSingleFiledirectorylinkSource );
                        }
                    }
                }
            }
        }
    }

    
Writes soft link from linkSource to directory for all files in the scanner.

Parameters:
directory Directory to link to.
linkSource Source to link from. Source.getLocation() must be a directory.
scanner Scanner used to scan the linSource location.
    private void linkScannedFilesString directoryfinal SoftlinkSource linkSourcefinal DirectoryScanner scanner )
    {
        final String[] files = scanner.getIncludedFiles();
        final String sourceLocation = linkSource.getLocation();
        final String targetPrefix = sourceLocation + .;
        final String sourcePrefix = directory + .;
        for ( String file : files )
        {
            .print"ln -s " );
            .printtargetPrefix + file );
            .print" $RPM_BUILD_ROOT/" );
            .printlnsourcePrefix + file );
            linkSource.getSourceMapping().addLinkedFileNameRelativeToDestinationfile );
        }
    }

    
Scans the buildSourceLocation using the Source.getIncludes() and Source.getExcludes() from linkSource. Returns the org.codehaus.plexus.util.DirectoryScanner used for scanning.

Parameters:
linkSource Source
buildSourceLocation Build location where content exists.
Returns:
org.codehaus.plexus.util.DirectoryScanner used for scanning.
    private static DirectoryScanner scanLinkSourcefinal SoftlinkSource linkSourcefinal File buildSourceLocation )
    {
        final DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedirbuildSourceLocation );
        List<Stringincludes = linkSource.getIncludes();
        scanner.setIncludes( ( includes == null || includes.isEmpty() ) ? null
                        : (String[]) includes.toArraynew String[includes.size()] ) );
        List<Stringexcludes = linkSource.getExcludes();
        scanner.setExcludes( ( excludes == null || excludes.isEmpty() ) ? null
                        : (String[]) excludes.toArraynew String[excludes.size()] ) );
        scanner.scan();
        return scanner;
    }

    
Assemble the RPM SPEC default file attributes.

Returns:
The attribute string for the SPEC file.
    private String getDefAttrString()
    {
        final String defaultFilemode = .getDefaultFilemode();
        final String defaultUsername = .getDefaultUsername();
        final String defaultGroupname = .getDefaultGroupname();
        final String defaultDirmode = .getDefaultDirmode();
        /* do not include %defattr if no default attributes are specified */
        if ( defaultFilemode == null && defaultUsername == null && defaultGroupname == null
            && .getDefaultDirmode() == null && defaultDirmode == null )
        {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        if ( defaultFilemode != null )
        {
            sb.append"%defattr(" ).appenddefaultFilemode ).append"," );
        }
        else
        {
            sb.append"%defattr(-," );
        }
        if ( defaultUsername != null )
        {
            sb.appenddefaultUsername ).append"," );
        }
        else
        {
            sb.append"-," );
        }
        if ( defaultGroupname != null )
        {
            sb.appenddefaultGroupname ).append"," );
        }
        else
        {
            sb.append"-," );
        }
        if ( defaultDirmode != null )
        {
            sb.appenddefaultDirmode ).append")" );
        }
        else
        {
            sb.append"-)" );
        }
        return sb.toString();
    }

    
Writes soft link from linkSource to directory using optional Source.getDestination() as the name of the link in directory if present.

Parameters:
directory Directory to link to.
linkSource Source to link from.
    private void linkSingleFileString directoryfinal SoftlinkSource linkSource )
    {
        .print"ln -s " );
        .printlinkSource.getLocation() );
        .print" $RPM_BUILD_ROOT/" );
        .printdirectory );
        .print'/' );
        final String destination = linkSource.getDestination();
        final String linkedFileName =
            destination == null ? new FilelinkSource.getMacroEvaluatedLocation() ).getName() : destination;
        .printlnlinkedFileName );
        linkSource.getSourceMapping().addLinkedFileNameRelativeToDestinationlinkedFileName );
    }

    
Writes all the scriptlets to the spec.
    private void writeScripts()
        throws IOException
    {
        // all scriptlets in order to write
        final Scriptlet[] scriptlets =
                .getPosttransScriptlet(), .getVerifyScriptlet(), .getCleanScriptlet() };
        // all directives, in parallel to scriptlets
        final String[] directives =
            new String[] { "%prep""%pretrans""%pre""%post""%preun""%postun""%posttrans""%verifyscript",
                "%clean" };
        for ( int i = 0; i < scriptlets.length; ++i )
        {
            if ( scriptlets[i] != null )
            {
                scriptlets[i].writedirectives[i] );
            }
        }
    }

    
Ifvalue is not null, writes the value to spec.

Writes in format: directive: value

Parameters:
directive
value
    private void writeNonNullDirectivefinal String directivefinal String value )
    {
        if ( value != null )
        {
            .printdirective );
            .print": " );
            .printlnvalue );
        }
    }

    
Writes a new line for each element in strings to the writer with the prefix.

Parameters:
strings List of Strings to write.
prefix Prefix to write on each line before the string.
    private void writeListCollection<StringstringsString prefix )
    {
        if ( strings != null )
        {
            for ( String str : strings )
            {
                if ( !str.equals"" ) )
                {
                    .printprefix );
                    .printlnstr );
                }
            }
        }
    }
New to GrepCode? Check out our FAQ X