Class FilePath
- java.lang.Object
-
- hudson.FilePath
-
- All Implemented Interfaces:
Serializable,org.jenkinsci.remoting.SerializableOnlyOverRemoting
public final class FilePath extends Object implements org.jenkinsci.remoting.SerializableOnlyOverRemoting
Filelike object with remoting support.Unlike
File, which always implies a file path on the current computer,FilePathrepresents a file path on a specific agent or the controller. Despite that,FilePathcan be used much likeFile. It exposes a bunch of operations (and we should add more operations as long as they are generally useful), and when invoked against a file on a remote node,FilePathexecutes the necessary code remotely, thereby providing semi-transparent file operations.Using
FilePathsmartlyThe transparency makes it easy to write plugins without worrying too much about remoting, by making it works like NFS, where remoting happens at the file-system layer.
But one should note that such use of remoting may not be optional. Sometimes, it makes more sense to move some computation closer to the data, as opposed to move the data to the computation. For example, if you are just computing a MD5 digest of a file, then it would make sense to do the digest on the host where the file is located, as opposed to send the whole data to the controller and do MD5 digesting there.
FilePathsupports this "code migration" by in theact(FileCallable)method. One can pass in a custom implementation ofFilePath.FileCallable, to be executed on the node where the data is located. The following code shows the example:void someMethod(FilePath file) { // make 'file' a fresh empty directory. file.act(new Freshen()); } // if 'file' is on a different node, this FileCallable will // be transferred to that node and executed there. private static final class Freshen implements FileCallable<Void> { private static final long serialVersionUID = 1; @Override public Void invoke(File f, VirtualChannel channel) { // f and file represent the same thing f.deleteContents(); f.mkdirs(); return null; } }When
FilePath.FileCallableis transferred to a remote node, it will be done so by using the same Java serialization scheme that the remoting module uses. SeeChannelfor more about this.FilePathitself can be sent over to a remote node as a part ofCallableserialization. For example, sending aFilePathof a remote node to that node causesFilePathto become "local". Similarly, sending aFilePaththat represents the local computer causes it to become "remote."- Author:
- Kohsuke Kawaguchi
- See Also:
VirtualFile, Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classFilePath.AbstractInterceptorCallableWrapper<T>AbstractDelegatingCallablethat exposes a Before/After pattern forFilePath.FileCallableWrapperFactorythat want to implement AOP-style interceptorsstatic classFilePath.DisplayOptionstatic classFilePath.ExplicitlySpecifiedDirScannerHelper class to make it easy to send an explicit list of files usingFilePathmethods.static interfaceFilePath.FileCallable<T>Code that gets executed on the machine where theFilePathis local.static classFilePath.FileCallableWrapperFactoryThis extension point allows to contribute a wrapper around a fileCallable so that a plugin can "intercept" a call.static classFilePath.FileMaskNoMatchesFoundExceptionA dedicated subtype ofInterruptedExceptionfor when no matching Ant file mask matches are found.static classFilePath.TarCompressionSupported tar file compression methods.
-
Field Summary
Fields Modifier and Type Field Description static hudson.remoting.LocalChannellocalChannelChannel to the current instance.static intSIDE_BUFFER_SIZEstatic intVALIDATE_ANT_FILE_MASK_BOUNDDefault bound forvalidateAntFileMask(String, int, boolean).
-
Constructor Summary
Constructors Constructor Description FilePath(FilePath base, String rel)Construct a path starting with a base location.FilePath(hudson.remoting.VirtualChannel channel, String remote)Creates aFilePaththat represents a path on the given node.FilePath(File localPath)To createFilePaththat represents a "local" path.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description FilePathabsolutize()Absolutizes thisFilePathand returns the new one.<T> Tact(FilePath.FileCallable<T> callable)Executes some program on the machine that thisFilePathexists, so that one can perform local file operations.<V,E extends Throwable>
Vact(hudson.remoting.Callable<V,E> callable)Executes some program on the machine that thisFilePathexists, so that one can perform local file operations.<T> hudson.remoting.Future<T>actAsync(FilePath.FileCallable<T> callable)Executes some program on the machine that thisFilePathexists, so that one can perform local file operations.intarchive(ArchiverFactory factory, OutputStream os, DirScanner scanner)Archives this directory into the specified archive format, to the givenOutputStream, by usingDirScannerto choose what files to include.intarchive(ArchiverFactory factory, OutputStream os, DirScanner scanner, String verificationRoot, OpenOption... openOptions)Archives this directory into the specified archive format, to the givenOutputStream, by usingDirScannerto choose what files to include.intarchive(ArchiverFactory factory, OutputStream os, FileFilter filter)intarchive(ArchiverFactory factory, OutputStream os, String glob)<V> hudson.remoting.Callable<V,IOException>asCallableWith(FilePath.FileCallable<V> task)FilePathchild(String relOrAbsolute)The same asFilePath(FilePath,String)but more OO.voidchmod(int mask)Sets the file permission.booleancontainsSymlink(FilePath verificationRoot, OpenOption... openOptions)voidcopyFrom(FilePath src)Convenience method to callcopyTo(FilePath).voidcopyFrom(InputStream in)Replaces the content of this file by the data from the givenInputStream.voidcopyFrom(URL url)Reads the URL on the current VM, and streams the data to this file using the Remoting channel.voidcopyFrom(org.apache.commons.fileupload.FileItem file)Place the data fromFileIteminto the file location specified by thisFilePathobject.intcopyRecursiveTo(FilePath target)Copies the contents of this directory recursively into the specified target directory.intcopyRecursiveTo(DirScanner scanner, FilePath target, String description)Copies files according to a specified scanner to a target node.intcopyRecursiveTo(DirScanner scanner, FilePath target, String description, FilePath.TarCompression compression)Copies files according to a specified scanner to a target node.intcopyRecursiveTo(String fileMask, FilePath target)Copies the files that match the given file mask to the specified target node.intcopyRecursiveTo(String fileMask, String excludes, FilePath target)Copies the files that match the given file mask to the specified target node.voidcopyTo(FilePath target)Copies this file to the specified target.voidcopyTo(OutputStream os)Sends the contents of this file into the givenOutputStream.voidcopyToWithPermission(FilePath target)Copies this file to the specified target, with file permissions and other meta attributes intact.LaunchercreateLauncher(TaskListener listener)Creates aLauncherfor starting processes on the node that has this file.FilePathcreateTempDir(String prefix, String suffix)Creates a temporary directory inside the directory represented by 'this'FilePathcreateTempFile(String prefix, String suffix)Creates a temporary file in the directory that thisFilePathobject designates.FilePathcreateTextTempFile(String prefix, String suffix, String contents)Creates a temporary file in this directory and set the contents to the given text (encoded in the platform default encoding)FilePathcreateTextTempFile(String prefix, String suffix, String contents, boolean inThisDirectory)Creates a temporary file in this directory (or the system temporary directory) and set the contents to the given text (encoded in the platform default encoding)voidcreateZipArchive(OutputStream os)Deprecated.as of 1.315.voidcreateZipArchive(OutputStream os, String glob)Deprecated.as of 1.315 Usezip(OutputStream,String)that has more consistent name.booleandelete()Deletes this file.voiddeleteContents()Deletes all the contents of this directory, but not the directory itselfvoiddeleteRecursive()Deletes this directory, including all its contents recursively.voiddeleteSuffixesRecursive()Deletes all suffixes recursively.Stringdigest()Computes the MD5 digest of the file in hex string.booleanequals(Object o)booleanexists()Checks if the file exists.StringgetBaseName()Gets the file name portion except the extension.hudson.remoting.VirtualChannelgetChannel()longgetFreeDiskSpace()Returns the number of unallocated bytes in the partition of that file.static FilePathgetHomeDirectory(hudson.remoting.VirtualChannel ch)Gets theFilePathrepresentation of the "~" directory (User's home directory in the Unix sense) of the given channel.StringgetName()Gets just the file name portion without directories.FilePathgetParent()Gets the parent file.StringgetRemote()Gets the full path of the file on the remote machine.longgetTotalDiskSpace()Returns the total number of bytes in the partition of that file.longgetUsableDiskSpace()Returns the number of usable bytes in the partition of that file.inthashCode()booleanhasSymlink(FilePath verificationRoot, OpenOption... openOptions)static FileVisitorignoringSymlinks(FileVisitor v, String verificationRoot, OpenOption... openOptions)WrapsFileVisitorto ignore symlinks.static FileVisitorignoringTmpDirs(FileVisitor v, String verificationRoot, OpenOption... openOptions)WrapsFileVisitorto ignore tmp directories.booleaninstallIfNecessaryFrom(URL archive, TaskListener listener, String message)Given a tgz/zip file, extracts it to the given target directory, if necessary.booleanisDescendant(String potentialChildRelativePath)Check if the relative child is really a descendant after symlink resolution if any.booleanisDirectory()Checks if the file is a directory.static booleanisIgnoreTmpDirs(OpenOption... openOptions)static booleanisNoFollowLink(OpenOption... openOptions)booleanisRemote()Returns true if thisFilePathrepresents a remote file.static booleanisSymlink(File file, String root, OpenOption... openOptions)static booleanisTmpDir(File file, String root, OpenOption... openOptions)static booleanisTmpDir(String filename, OpenOption... openOptions)longlastModified()Gets the last modified time stamp of this file, by using the clock of the machine where this file actually resides.longlength()Returns the file size in bytes.List<FilePath>list()List up files and directories in this directory.List<FilePath>list(FilePath verificationRoot, OpenOption... openOptions)List up files and directories in this directory.List<FilePath>list(FileFilter filter)List up files in this directory, just likeFile.listFiles(FileFilter).FilePath[]list(String includes)List up files in this directory that matches the given Ant-style filter.FilePath[]list(String includes, String excludes)List up files in this directory that matches the given Ant-style filter.FilePath[]list(String includes, String excludes, boolean defaultExcludes)List up files in this directory that matches the given Ant-style filter.List<FilePath>listDirectories()List up subdirectories.voidmkdirs()Creates this directory.intmode()Gets the file permission bit mask.voidmoveAllChildrenTo(FilePath target)Moves all the contents of this directory into the specified directory, then delete this directory itself.static InputStreamnewInputStreamDenyingSymlinkAsNeeded(File file, String verificationRoot, OpenOption... openOptions)static Stringnormalize(String path)File.getParent()etc cannot handle ".." and "." in the path component very well, so remove them.static InputStreamopenInputStream(File file, OpenOption[] openOptions)InputStreamread()Reads this file.InputStreamread(FilePath rootPath, OpenOption... openOptions)InputStreamreadFromOffset(long offset)Reads this file from the specific offset.StringreadLink()Resolves symlink, if the given file is a symlink.StringreadToString()Reads this file into a string, by using the current system encoding on the remote machine.voidrenameTo(FilePath target)Rename this file/directory to the target filepath.FilePathsibling(String rel)Short forgetParent().child(rel).voidsymlinkTo(String target, TaskListener listener)Creates a symlink to the specified target.inttar(OutputStream out, DirScanner scanner)Uses the given scanner on 'this' directory to list up files and then archive it to a tar stream.inttar(OutputStream out, FileFilter filter)inttar(OutputStream out, String glob)Writes files in 'this' directory to a tar stream.ComputertoComputer()StringtoString()Deprecated.voidtouch(long timestamp)Creates a file (if not already exist) and sets the timestamp.URItoURI()Converts this file to the URI, relative to the machine on which this file is available.VirtualFiletoVirtualFile()Gets theVirtualFilerepresentation of thisFilePathvoiduntar(FilePath target, FilePath.TarCompression compression)When thisFilePathrepresents a tar file, extracts that tar file.voiduntarFrom(InputStream _in, FilePath.TarCompression compression)Reads the given InputStream as a tar file and extracts it into this directory.voidunzip(FilePath target)When thisFilePathrepresents a zip file, extracts that zip file.voidunzipFrom(InputStream _in)Reads the given InputStream as a zip file and extracts it into this directory.StringvalidateAntFileMask(String fileMasks)Deprecated.usevalidateAntFileMask(String, int)insteadStringvalidateAntFileMask(String fileMasks, boolean caseSensitive)Same asvalidateAntFileMask(String, int, boolean)with the default number of operations.StringvalidateAntFileMask(String fileMasks, int bound)Same asvalidateAntFileMask(String, int, boolean)with caseSensitive set to true.StringvalidateAntFileMask(String fileMasks, int bound, boolean caseSensitive)Validates the ant file mask (like "foo/bar/*.txt, zot/*.jar") against this directory, and try to point out the problem.static FormValidationvalidateFileMask(FilePath path, String value)Short forvalidateFileMask(path, value, true)static FormValidationvalidateFileMask(FilePath path, String value, boolean caseSensitive)Shortcut forvalidateFileMask(String,boolean,boolean)witherrorIfNotExisttrue, as the left-hand side can be null.FormValidationvalidateFileMask(String value)Short forvalidateFileMask(value, true, true)FormValidationvalidateFileMask(String value, boolean errorIfNotExist)Short forvalidateFileMask(value, errorIfNotExist, true)FormValidationvalidateFileMask(String value, boolean errorIfNotExist, boolean caseSensitive)Checks the GLOB-style file mask.FormValidationvalidateRelativeDirectory(String value)FormValidationvalidateRelativeDirectory(String value, boolean errorIfNotExist)A convenience method overvalidateRelativePath(String, boolean, boolean).FormValidationvalidateRelativePath(String value, boolean errorIfNotExist, boolean expectingFile)Validates a relative file path from thisFilePath.FilePathwithSuffix(String suffix)Returns aFilePathby adding the given suffix to this path name.OutputStreamwrite()Writes to this file.voidwrite(String content, String encoding)Overwrites this file by placing the given String as the content.voidzip(FilePath dst)voidzip(OutputStream os)Creates a zip file from this directory or a file and sends that to the given output stream.intzip(OutputStream out, DirScanner scanner)Uses the given scanner on 'this' directory to list up files and then archive it to a zip stream.intzip(OutputStream out, DirScanner scanner, String verificationRoot, String prefix, OpenOption... openOptions)Uses the given scanner on 'this' directory to list up files and then archive it to a zip stream.voidzip(OutputStream os, FileFilter filter)Creates a zip file from this directory by using the specified filter, and sends the result to the given output stream.voidzip(OutputStream os, String glob)Creates a zip file from this directory by only including the files that match the given glob.
-
-
-
Field Detail
-
VALIDATE_ANT_FILE_MASK_BOUND
public static int VALIDATE_ANT_FILE_MASK_BOUND
Default bound forvalidateAntFileMask(String, int, boolean).- Since:
- 1.592
-
SIDE_BUFFER_SIZE
@Restricted(org.kohsuke.accmod.restrictions.NoExternalUse.class) @RestrictedSince("2.328") public static final int SIDE_BUFFER_SIZE
- See Also:
- Constant Field Values
-
localChannel
@NonNull public static final hudson.remoting.LocalChannel localChannel
Channel to the current instance.
-
-
Constructor Detail
-
FilePath
public FilePath(@CheckForNull hudson.remoting.VirtualChannel channel, @NonNull String remote)Creates aFilePaththat represents a path on the given node.- Parameters:
channel- To create a path that represents a remote path, pass in aChannelthat's connected to that machine. Ifnull, that means the local file path.
-
FilePath
public FilePath(@NonNull File localPath)To createFilePaththat represents a "local" path.A "local" path means a file path on the computer where the constructor invocation happened.
-
-
Method Detail
-
normalize
@Restricted(org.kohsuke.accmod.restrictions.NoExternalUse.class) public static String normalize(@NonNull String path)
File.getParent()etc cannot handle ".." and "." in the path component very well, so remove them.
-
getRemote
public String getRemote()
Gets the full path of the file on the remote machine.
-
createZipArchive
@Deprecated public void createZipArchive(OutputStream os) throws IOException, InterruptedException
Deprecated.as of 1.315. Usezip(OutputStream)that has more consistent name.Creates a zip file from this directory or a file and sends that to the given output stream.- Throws:
IOExceptionInterruptedException
-
zip
public void zip(OutputStream os) throws IOException, InterruptedException
Creates a zip file from this directory or a file and sends that to the given output stream.- Throws:
IOExceptionInterruptedException
-
zip
public void zip(FilePath dst) throws IOException, InterruptedException
- Throws:
IOExceptionInterruptedException
-
zip
public void zip(OutputStream os, FileFilter filter) throws IOException, InterruptedException
Creates a zip file from this directory by using the specified filter, and sends the result to the given output stream.- Parameters:
filter- Must be serializable since it may be executed remotely. Can be null to add all files.- Throws:
IOExceptionInterruptedException- Since:
- 1.315
-
createZipArchive
@Deprecated public void createZipArchive(OutputStream os, String glob) throws IOException, InterruptedException
Deprecated.as of 1.315 Usezip(OutputStream,String)that has more consistent name.Creates a zip file from this directory by only including the files that match the given glob.- Parameters:
glob- Ant style glob, like "**/*.xml". If empty or null, this method works likecreateZipArchive(OutputStream)- Throws:
IOExceptionInterruptedException- Since:
- 1.129
-
zip
public void zip(OutputStream os, String glob) throws IOException, InterruptedException
Creates a zip file from this directory by only including the files that match the given glob.- Parameters:
glob- Ant style glob, like "**/*.xml". If empty or null, this method works likecreateZipArchive(OutputStream), inserting a top-level directory into the ZIP.- Throws:
IOExceptionInterruptedException- Since:
- 1.315
-
zip
public int zip(OutputStream out, DirScanner scanner) throws IOException, InterruptedException
Uses the given scanner on 'this' directory to list up files and then archive it to a zip stream.- Throws:
IOExceptionInterruptedException
-
zip
public int zip(OutputStream out, DirScanner scanner, String verificationRoot, String prefix, OpenOption... openOptions) throws IOException, InterruptedException
Uses the given scanner on 'this' directory to list up files and then archive it to a zip stream.- Parameters:
out- The OutputStream to write the zip into.scanner- A DirScanner for scanning the directory and filtering its contents.verificationRoot- A root or base directory for checking for any symlinks in this files parentage. Any symlinks between a file and root should be ignored. Symlinks in the parentage outside root will not be checked.prefix- The portion of file path that will be added at the beginning of the relative path inside the archive. If non-empty, a trailing forward slash will be enforced.openOptions- the options to apply when opening.- Returns:
- The number of files/directories archived. This is only really useful to check for a situation where nothing
- Throws:
IOExceptionInterruptedException
-
archive
public int archive(ArchiverFactory factory, OutputStream os, DirScanner scanner) throws IOException, InterruptedException
Archives this directory into the specified archive format, to the givenOutputStream, by usingDirScannerto choose what files to include.- Returns:
- number of files/directories archived. This is only really useful to check for a situation where nothing is archived.
- Throws:
IOExceptionInterruptedException
-
archive
public int archive(ArchiverFactory factory, OutputStream os, DirScanner scanner, String verificationRoot, OpenOption... openOptions) throws IOException, InterruptedException
Archives this directory into the specified archive format, to the givenOutputStream, by usingDirScannerto choose what files to include.- Parameters:
factory- The ArchiverFactory for creating the archive.os- The OutputStream to write the zip into.verificationRoot- A root or base directory for checking for any symlinks in this files parentage. Any symlinks between a file and root should be ignored. Symlinks in the parentage outside root will not be checked.openOptions- options to apply when opening.- Returns:
- The number of files/directories archived. This is only really useful to check for a situation where nothing
- Throws:
IOExceptionInterruptedException
-
archive
public int archive(ArchiverFactory factory, OutputStream os, FileFilter filter) throws IOException, InterruptedException
- Throws:
IOExceptionInterruptedException
-
archive
public int archive(ArchiverFactory factory, OutputStream os, String glob) throws IOException, InterruptedException
- Throws:
IOExceptionInterruptedException
-
unzip
public void unzip(FilePath target) throws IOException, InterruptedException
When thisFilePathrepresents a zip file, extracts that zip file.- Parameters:
target- Target directory to expand files to. All the necessary directories will be created.- Throws:
IOExceptionInterruptedException- Since:
- 1.248
- See Also:
unzipFrom(InputStream)
-
untar
public void untar(FilePath target, FilePath.TarCompression compression) throws IOException, InterruptedException
When thisFilePathrepresents a tar file, extracts that tar file.- Parameters:
target- Target directory to expand files to. All the necessary directories will be created.compression- Compression mode of this tar file.- Throws:
IOExceptionInterruptedException- Since:
- 1.292
- See Also:
untarFrom(InputStream, TarCompression)
-
unzipFrom
public void unzipFrom(InputStream _in) throws IOException, InterruptedException
Reads the given InputStream as a zip file and extracts it into this directory.- Parameters:
_in- The stream will be closed by this method after it's fully read.- Throws:
IOExceptionInterruptedException- Since:
- 1.283
- See Also:
unzip(FilePath)
-
absolutize
public FilePath absolutize() throws IOException, InterruptedException
Absolutizes thisFilePathand returns the new one.- Throws:
IOExceptionInterruptedException
-
hasSymlink
public boolean hasSymlink(FilePath verificationRoot, OpenOption... openOptions) throws IOException, InterruptedException
- Throws:
IOExceptionInterruptedException
-
containsSymlink
public boolean containsSymlink(FilePath verificationRoot, OpenOption... openOptions) throws IOException, InterruptedException
- Throws:
IOExceptionInterruptedException
-
symlinkTo
public void symlinkTo(String target, TaskListener listener) throws IOException, InterruptedException
Creates a symlink to the specified target.- Parameters:
target- The file that the symlink should point to.listener- If symlink creation requires a help of an external process, the error will be reported here.- Throws:
IOExceptionInterruptedException- Since:
- 1.456
-
readLink
public String readLink() throws IOException, InterruptedException
Resolves symlink, if the given file is a symlink. Otherwise, return null.If the resolution fails, report an error.
- Throws:
IOExceptionInterruptedException- Since:
- 1.456
-
untarFrom
public void untarFrom(InputStream _in, FilePath.TarCompression compression) throws IOException, InterruptedException
Reads the given InputStream as a tar file and extracts it into this directory.- Parameters:
_in- The stream will be closed by this method after it's fully read.compression- The compression method in use.- Throws:
IOExceptionInterruptedException- Since:
- 1.292
-
installIfNecessaryFrom
public boolean installIfNecessaryFrom(@NonNull URL archive, @CheckForNull TaskListener listener, @NonNull String message) throws IOException, InterruptedExceptionGiven a tgz/zip file, extracts it to the given target directory, if necessary.This method is a convenience method designed for installing a binary package to a location that supports upgrade and downgrade. Specifically,
- If the target directory doesn't exist it will be created.
- The timestamp of the archive is left in the installation directory upon extraction.
- If the timestamp left in the directory does not match the timestamp of the current archive file, the directory contents will be discarded and the archive file will be re-extracted.
- If the connection is refused but the target directory already exists, it is left alone.
- Parameters:
archive- The resource that represents the tgz/zip file. This URL must support theLast-Modifiedheader or theETagheader. (For example, you could useClassLoader.getResource(java.lang.String).)listener- If non-null, a message will be printed to this listener once this method decides to extract an archive, or if there is any issue.message- a message to be printed in case extraction will proceed.- Returns:
- true if the archive was extracted. false if the extraction was skipped because the target directory was considered up to date.
- Throws:
IOExceptionInterruptedException- Since:
- 1.299
-
copyFrom
public void copyFrom(URL url) throws IOException, InterruptedException
Reads the URL on the current VM, and streams the data to this file using the Remoting channel.This is different from resolving URL remotely. If you instead wished to open an HTTP(S) URL on the remote side, prefer
RobustHTTPClient.copyFromRemotely.- Throws:
IOExceptionInterruptedException- Since:
- 1.293
-
copyFrom
public void copyFrom(InputStream in) throws IOException, InterruptedException
Replaces the content of this file by the data from the givenInputStream.- Throws:
IOExceptionInterruptedException- Since:
- 1.293
-
copyFrom
public void copyFrom(FilePath src) throws IOException, InterruptedException
Convenience method to callcopyTo(FilePath).- Throws:
IOExceptionInterruptedException- Since:
- 1.311
-
copyFrom
public void copyFrom(org.apache.commons.fileupload.FileItem file) throws IOException, InterruptedExceptionPlace the data fromFileIteminto the file location specified by thisFilePathobject.- Throws:
IOExceptionInterruptedException
-
act
public <T> T act(FilePath.FileCallable<T> callable) throws IOException, InterruptedException
Executes some program on the machine that thisFilePathexists, so that one can perform local file operations.- Throws:
IOExceptionInterruptedException
-
actAsync
public <T> hudson.remoting.Future<T> actAsync(FilePath.FileCallable<T> callable) throws IOException, InterruptedException
Executes some program on the machine that thisFilePathexists, so that one can perform local file operations.- Throws:
IOExceptionInterruptedException
-
act
public <V,E extends Throwable> V act(hudson.remoting.Callable<V,E> callable) throws IOException, InterruptedException, E extends Throwable
Executes some program on the machine that thisFilePathexists, so that one can perform local file operations.- Throws:
IOExceptionInterruptedExceptionE extends Throwable
-
asCallableWith
public <V> hudson.remoting.Callable<V,IOException> asCallableWith(FilePath.FileCallable<V> task)
Takes aFilePath+FilePath.FileCallablepair and returns the equivalentCallable. When executing the resultingCallable, it executesact(FileCallable)on thisFilePath.- Since:
- 1.522
-
toURI
public URI toURI() throws IOException, InterruptedException
Converts this file to the URI, relative to the machine on which this file is available.- Throws:
IOExceptionInterruptedException
-
toVirtualFile
public VirtualFile toVirtualFile()
Gets theVirtualFilerepresentation of thisFilePath- Since:
- 1.532
-
toComputer
@CheckForNull public Computer toComputer()
- Since:
- 1.571
-
mkdirs
public void mkdirs() throws IOException, InterruptedExceptionCreates this directory.- Throws:
IOExceptionInterruptedException
-
deleteSuffixesRecursive
public void deleteSuffixesRecursive() throws IOException, InterruptedExceptionDeletes all suffixes recursively.- Throws:
IOException- if it exists but could not be successfully deletedInterruptedException- Since:
- 2.244
-
deleteRecursive
public void deleteRecursive() throws IOException, InterruptedExceptionDeletes this directory, including all its contents recursively.- Throws:
IOExceptionInterruptedException
-
deleteContents
public void deleteContents() throws IOException, InterruptedExceptionDeletes all the contents of this directory, but not the directory itself- Throws:
IOExceptionInterruptedException
-
getBaseName
public String getBaseName()
Gets the file name portion except the extension. For example, "foo" for "foo.txt" and "foo.tar" for "foo.tar.gz".
-
getName
public String getName()
Gets just the file name portion without directories. For example, "foo.txt" for "../abc/foo.txt"
-
sibling
@CheckForNull public FilePath sibling(String rel)
Short forgetParent().child(rel). Useful for getting other files in the same directory.- Returns:
- null if
getParent()would have
-
withSuffix
public FilePath withSuffix(String suffix)
Returns aFilePathby adding the given suffix to this path name.
-
child
@NonNull public FilePath child(String relOrAbsolute)
The same asFilePath(FilePath,String)but more OO.- Parameters:
relOrAbsolute- a relative or absolute path- Returns:
- a file on the same channel
-
getParent
@CheckForNull public FilePath getParent()
Gets the parent file.- Returns:
- parent FilePath or null if there is no parent
-
createTempFile
public FilePath createTempFile(String prefix, String suffix) throws IOException, InterruptedException
Creates a temporary file in the directory that thisFilePathobject designates.- Parameters:
prefix- The prefix string to be used in generating the file's name; must be at least three characters longsuffix- The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be used- Returns:
- The new FilePath pointing to the temporary file
- Throws:
IOExceptionInterruptedException- See Also:
File.createTempFile(String, String)
-
createTextTempFile
public FilePath createTextTempFile(String prefix, String suffix, String contents) throws IOException, InterruptedException
Creates a temporary file in this directory and set the contents to the given text (encoded in the platform default encoding)- Parameters:
prefix- The prefix string to be used in generating the file's name; must be at least three characters longsuffix- The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be usedcontents- The initial contents of the temporary file.- Returns:
- The new FilePath pointing to the temporary file
- Throws:
IOExceptionInterruptedException- See Also:
File.createTempFile(String, String)
-
createTextTempFile
public FilePath createTextTempFile(String prefix, String suffix, String contents, boolean inThisDirectory) throws IOException, InterruptedException
Creates a temporary file in this directory (or the system temporary directory) and set the contents to the given text (encoded in the platform default encoding)- Parameters:
prefix- The prefix string to be used in generating the file's name; must be at least three characters longsuffix- The suffix string to be used in generating the file's name; may be null, in which case the suffix ".tmp" will be usedcontents- The initial contents of the temporary file.inThisDirectory- If true, then create this temporary in the directory pointed to by this. If false, then the temporary file is created in the system temporary directory (java.io.tmpdir)- Returns:
- The new FilePath pointing to the temporary file
- Throws:
IOExceptionInterruptedException- See Also:
File.createTempFile(String, String)
-
createTempDir
public FilePath createTempDir(String prefix, String suffix) throws IOException, InterruptedException
Creates a temporary directory inside the directory represented by 'this'- Parameters:
prefix- The prefix string to be used in generating the directory's name; must be at least three characters longsuffix- The suffix string to be used in generating the directory's name; may be null, in which case the suffix ".tmp" will be used- Returns:
- The new FilePath pointing to the temporary directory
- Throws:
IOExceptionInterruptedException- Since:
- 1.311
- See Also:
Files.createTempDirectory(Path, String, FileAttribute[])
-
delete
public boolean delete() throws IOException, InterruptedExceptionDeletes this file.- Returns:
- true, for a modicum of compatibility
- Throws:
IOException- if it exists but could not be successfully deletedInterruptedException
-
exists
public boolean exists() throws IOException, InterruptedExceptionChecks if the file exists.- Throws:
IOExceptionInterruptedException
-
lastModified
public long lastModified() throws IOException, InterruptedExceptionGets the last modified time stamp of this file, by using the clock of the machine where this file actually resides.- Throws:
IOExceptionInterruptedException- See Also:
File.lastModified(),touch(long)
-
touch
public void touch(long timestamp) throws IOException, InterruptedExceptionCreates a file (if not already exist) and sets the timestamp.- Throws:
IOExceptionInterruptedException- Since:
- 1.299
-
isDirectory
public boolean isDirectory() throws IOException, InterruptedExceptionChecks if the file is a directory.- Throws:
IOExceptionInterruptedException
-
length
public long length() throws IOException, InterruptedExceptionReturns the file size in bytes.- Throws:
IOExceptionInterruptedException- Since:
- 1.129
-
getFreeDiskSpace
public long getFreeDiskSpace() throws IOException, InterruptedExceptionReturns the number of unallocated bytes in the partition of that file.- Throws:
IOExceptionInterruptedException- Since:
- 1.542
-
getTotalDiskSpace
public long getTotalDiskSpace() throws IOException, InterruptedExceptionReturns the total number of bytes in the partition of that file.- Throws:
IOExceptionInterruptedException- Since:
- 1.542
-
getUsableDiskSpace
public long getUsableDiskSpace() throws IOException, InterruptedExceptionReturns the number of usable bytes in the partition of that file.- Throws:
IOExceptionInterruptedException- Since:
- 1.542
-
chmod
public void chmod(int mask) throws IOException, InterruptedExceptionSets the file permission. On Windows, no-op.- Parameters:
mask- File permission mask. To simplify the permission copying, if the parameter is -1, this method becomes no-op.please note mask is expected to be an octal if you use chmod command line values, so preceded by a '0' in java notation, ie
chmod(0644)Only supports setting read, write, or execute permissions for the owner, group, or others, so the largest permissible value is 0777. Attempting to set larger values (i.e. the setgid, setuid, or sticky bits) will cause an IOException to be thrown.
- Throws:
IOExceptionInterruptedException- Since:
- 1.303
- See Also:
mode()
-
mode
public int mode() throws IOException, InterruptedExceptionGets the file permission bit mask.- Returns:
- -1 on Windows, since such a concept doesn't make sense.
- Throws:
IOExceptionInterruptedException- Since:
- 1.311
- See Also:
chmod(int)
-
list
@NonNull public List<FilePath> list() throws IOException, InterruptedException
List up files and directories in this directory.This method returns direct children of the directory denoted by the 'this' object.
- Throws:
IOExceptionInterruptedException
-
list
@NonNull public List<FilePath> list(FilePath verificationRoot, OpenOption... openOptions) throws IOException, InterruptedException
List up files and directories in this directory. This is intended to allow the caller to provideLinkOption.NOFOLLOW_LINKSto ignore symlinks.- Parameters:
verificationRoot- A root or base directory for checking for any symlinks in this files parentage. Any symlinks between a file and root should be ignored. Symlinks in the parentage outside root will not be checked.openOptions- the options to apply when opening.- Returns:
- Direct children of this directory.
- Throws:
IOExceptionInterruptedException
-
listDirectories
@NonNull public List<FilePath> listDirectories() throws IOException, InterruptedException
List up subdirectories.- Returns:
- can be empty but never null. Doesn't contain "." and ".."
- Throws:
IOExceptionInterruptedException
-
list
@NonNull public List<FilePath> list(FileFilter filter) throws IOException, InterruptedException
List up files in this directory, just likeFile.listFiles(FileFilter).- Parameters:
filter- The optional filter used to narrow down the result. If non-null, must beSerializable. If thisFilePathrepresents a remote path, the filter object will be executed on the remote machine.- Throws:
IOExceptionInterruptedException
-
list
@NonNull public FilePath[] list(String includes) throws IOException, InterruptedException
List up files in this directory that matches the given Ant-style filter.- Parameters:
includes- SeeFileSetfor the syntax. String like "foo/*.zip" or "foo/**/*.xml"- Returns:
- can be empty but always non-null.
- Throws:
IOExceptionInterruptedException
-
list
@NonNull public FilePath[] list(String includes, String excludes) throws IOException, InterruptedException
List up files in this directory that matches the given Ant-style filter.- Parameters:
includes- SeeFileSetfor the syntax. String like "foo/*.zip" or "foo/**/*.xml"excludes- SeeFileSetfor the syntax. String like "foo/*.zip" or "foo/**/*.xml"- Returns:
- can be empty but always non-null.
- Throws:
IOExceptionInterruptedException- Since:
- 1.407
-
list
@NonNull public FilePath[] list(String includes, String excludes, boolean defaultExcludes) throws IOException, InterruptedException
List up files in this directory that matches the given Ant-style filter.- Parameters:
includes- SeeFileSetfor the syntax. String like "foo/*.zip" or "foo/**/*.xml"excludes- SeeFileSetfor the syntax. String like "foo/*.zip" or "foo/**/*.xml"defaultExcludes- whether to use the ant default excludes- Returns:
- can be empty but always non-null.
- Throws:
IOExceptionInterruptedException- Since:
- 1.465
-
read
public InputStream read() throws IOException, InterruptedException
Reads this file.- Throws:
IOExceptionInterruptedException
-
read
public InputStream read(FilePath rootPath, OpenOption... openOptions) throws IOException, InterruptedException
- Throws:
IOExceptionInterruptedException
-
newInputStreamDenyingSymlinkAsNeeded
public static InputStream newInputStreamDenyingSymlinkAsNeeded(File file, String verificationRoot, OpenOption... openOptions) throws IOException
- Throws:
IOException
-
openInputStream
public static InputStream openInputStream(File file, OpenOption[] openOptions) throws IOException
- Throws:
IOException
-
isSymlink
public static boolean isSymlink(File file, String root, OpenOption... openOptions)
-
isTmpDir
public static boolean isTmpDir(File file, String root, OpenOption... openOptions)
-
isTmpDir
public static boolean isTmpDir(String filename, OpenOption... openOptions)
-
isNoFollowLink
public static boolean isNoFollowLink(OpenOption... openOptions)
-
isIgnoreTmpDirs
public static boolean isIgnoreTmpDirs(OpenOption... openOptions)
-
readFromOffset
public InputStream readFromOffset(long offset) throws IOException, InterruptedException
Reads this file from the specific offset.- Throws:
IOExceptionInterruptedException- Since:
- 1.586
-
readToString
public String readToString() throws IOException, InterruptedException
Reads this file into a string, by using the current system encoding on the remote machine.- Throws:
IOExceptionInterruptedException
-
write
public OutputStream write() throws IOException, InterruptedException
Writes to this file. If this file already exists, it will be overwritten. If the directory doesn't exist, it will be created.I/O operation to remote
FilePathhappens asynchronously, meaning write operations to the returnedOutputStreamwill return without receiving a confirmation from the remote that the write happened. I/O operations also happens asynchronously from theChannel.call(Callable)operations, so if you write to a remote file and then executeChannel.call(Callable)and try to access the newly copied file, it might not be fully written yet.- Throws:
IOExceptionInterruptedException
-
write
public void write(String content, String encoding) throws IOException, InterruptedException
Overwrites this file by placing the given String as the content.- Parameters:
encoding- Null to use the platform default encoding on the remote machine.- Throws:
IOExceptionInterruptedException- Since:
- 1.105
-
digest
public String digest() throws IOException, InterruptedException
Computes the MD5 digest of the file in hex string.- Throws:
IOExceptionInterruptedException- See Also:
Util.getDigestOf(File)
-
renameTo
public void renameTo(FilePath target) throws IOException, InterruptedException
Rename this file/directory to the target filepath. This FilePath and the target must be on the same host- Throws:
IOExceptionInterruptedException
-
moveAllChildrenTo
public void moveAllChildrenTo(FilePath target) throws IOException, InterruptedException
Moves all the contents of this directory into the specified directory, then delete this directory itself.- Throws:
IOExceptionInterruptedException- Since:
- 1.308.
-
copyTo
public void copyTo(FilePath target) throws IOException, InterruptedException
Copies this file to the specified target.- Throws:
IOExceptionInterruptedException
-
copyToWithPermission
public void copyToWithPermission(FilePath target) throws IOException, InterruptedException
Copies this file to the specified target, with file permissions and other meta attributes intact.- Throws:
IOExceptionInterruptedException- Since:
- 1.311
-
copyTo
public void copyTo(OutputStream os) throws IOException, InterruptedException
Sends the contents of this file into the givenOutputStream.- Throws:
IOExceptionInterruptedException
-
copyRecursiveTo
public int copyRecursiveTo(FilePath target) throws IOException, InterruptedException
Copies the contents of this directory recursively into the specified target directory.- Returns:
- the number of files copied.
- Throws:
IOExceptionInterruptedException- Since:
- 1.312
-
copyRecursiveTo
public int copyRecursiveTo(String fileMask, FilePath target) throws IOException, InterruptedException
Copies the files that match the given file mask to the specified target node.- Parameters:
fileMask- Ant GLOB pattern. String like "foo/bar/*.xml" Multiple patterns can be separated by ',', and whitespace can surround ',' so that you can write "abc, def" and "abc,def" to mean the same thing.- Returns:
- the number of files copied.
- Throws:
IOExceptionInterruptedException
-
copyRecursiveTo
public int copyRecursiveTo(String fileMask, String excludes, FilePath target) throws IOException, InterruptedException
Copies the files that match the given file mask to the specified target node.- Parameters:
fileMask- Ant GLOB pattern. String like "foo/bar/*.xml" Multiple patterns can be separated by ',', and whitespace can surround ',' so that you can write "abc, def" and "abc,def" to mean the same thing.excludes- Files to be excluded. Can be null.- Returns:
- the number of files copied.
- Throws:
IOExceptionInterruptedException
-
copyRecursiveTo
public int copyRecursiveTo(DirScanner scanner, FilePath target, String description) throws IOException, InterruptedException
Copies files according to a specified scanner to a target node.- Parameters:
scanner- a way of enumerating some files (must be serializable for possible delivery to remote side)target- the destination basedirdescription- a description of the fileset, for logging purposes- Returns:
- the number of files copied
- Throws:
IOExceptionInterruptedException- Since:
- 1.532
-
copyRecursiveTo
public int copyRecursiveTo(DirScanner scanner, FilePath target, String description, @NonNull FilePath.TarCompression compression) throws IOException, InterruptedException
Copies files according to a specified scanner to a target node.- Parameters:
scanner- a way of enumerating some files (must be serializable for possible delivery to remote side)target- the destination basedirdescription- a description of the fileset, for logging purposescompression- compression to use- Returns:
- the number of files copied
- Throws:
IOExceptionInterruptedException- Since:
- 2.196
-
tar
public int tar(OutputStream out, String glob) throws IOException, InterruptedException
Writes files in 'this' directory to a tar stream.- Parameters:
glob- Ant file pattern mask, like "**/*.java".- Throws:
IOExceptionInterruptedException
-
tar
public int tar(OutputStream out, FileFilter filter) throws IOException, InterruptedException
- Throws:
IOExceptionInterruptedException
-
tar
public int tar(OutputStream out, DirScanner scanner) throws IOException, InterruptedException
Uses the given scanner on 'this' directory to list up files and then archive it to a tar stream.- Throws:
IOExceptionInterruptedException
-
createLauncher
public Launcher createLauncher(TaskListener listener) throws IOException, InterruptedException
Creates aLauncherfor starting processes on the node that has this file.- Throws:
IOExceptionInterruptedException- Since:
- 1.89
-
validateAntFileMask
@Deprecated public String validateAntFileMask(String fileMasks) throws IOException, InterruptedException
Deprecated.usevalidateAntFileMask(String, int)insteadSame asvalidateAntFileMask(String, int)with (practically) unbounded number of operations.- Returns:
- null if no error was found. Otherwise, returns a human-readable error message.
- Throws:
IOExceptionInterruptedException- Since:
- 1.90
- See Also:
validateFileMask(FilePath, String)
-
validateAntFileMask
public String validateAntFileMask(String fileMasks, int bound) throws IOException, InterruptedException
Same asvalidateAntFileMask(String, int, boolean)with caseSensitive set to true.- Throws:
IOExceptionInterruptedException
-
validateAntFileMask
public String validateAntFileMask(String fileMasks, boolean caseSensitive) throws IOException, InterruptedException
Same asvalidateAntFileMask(String, int, boolean)with the default number of operations.- Throws:
IOExceptionInterruptedException- Since:
- 2.325
- See Also:
VALIDATE_ANT_FILE_MASK_BOUND
-
validateAntFileMask
@CheckForNull public String validateAntFileMask(String fileMasks, int bound, boolean caseSensitive) throws IOException, InterruptedException
Validates the ant file mask (like "foo/bar/*.txt, zot/*.jar") against this directory, and try to point out the problem. This performs only a bounded number of operations.Whereas the unbounded overload is appropriate for calling from cancelable, long-running tasks such as build steps, this overload should be used when an answer is needed quickly, such as for
validateFileMask(String)or anything else returningFormValidation.If a positive match is found,
nullis returned immediately. A message is returned in case the file pattern can definitely be determined to not match anything in the directory within the alloted time. If the time runs out without finding a match but without ruling out the possibility that there might be one,InterruptedExceptionis thrown, in which case the calling code should give the user the benefit of the doubt and useFormValidation.Kind.OK(with or without a message).While this can be used in conjunction with
FormValidation, it's generally better to usevalidateFileMask(String)and its overloads for use indoCheckform validation methods related to workspaces, as that performs an appropriate permission check. Callers of this method or its overloads from web methods should ensure permissions are checked before this method is invoked.- Parameters:
bound- a maximum number of negative operations (deliberately left vague) to perform before giving up on a precise answer; tryVALIDATE_ANT_FILE_MASK_BOUND- Throws:
InterruptedException- not only in case of a channel failure, but also if too many operations were performed without finding any matchesIOException- Since:
- 1.484
-
validateFileMask
public static FormValidation validateFileMask(@CheckForNull FilePath path, String value) throws IOException
Short forvalidateFileMask(path, value, true)- Throws:
IOException
-
validateFileMask
public static FormValidation validateFileMask(@CheckForNull FilePath path, String value, boolean caseSensitive) throws IOException
Shortcut forvalidateFileMask(String,boolean,boolean)witherrorIfNotExisttrue, as the left-hand side can be null.- Throws:
IOException
-
validateFileMask
public FormValidation validateFileMask(String value) throws IOException
Short forvalidateFileMask(value, true, true)- Throws:
IOException
-
validateFileMask
public FormValidation validateFileMask(String value, boolean errorIfNotExist) throws IOException
Short forvalidateFileMask(value, errorIfNotExist, true)- Throws:
IOException
-
validateFileMask
public FormValidation validateFileMask(String value, boolean errorIfNotExist, boolean caseSensitive) throws IOException
Checks the GLOB-style file mask. SeevalidateAntFileMask(String). Requires configure permission on ancestorAbstractProjectobject in request, orJenkins.MANAGEpermission if no such ancestor is found.Note that this permission check may not always make sense based on the directory provided; callers should consider using
validateFileMask(FilePath, String, boolean)and its overloads instead (once appropriate permission checks have succeeded).- Throws:
IOException- Since:
- 1.294
-
validateRelativePath
public FormValidation validateRelativePath(String value, boolean errorIfNotExist, boolean expectingFile) throws IOException
Validates a relative file path from thisFilePath. Requires configure permission on ancestorAbstractProjectobject in request, orJenkins.MANAGEpermission if no such ancestor is found.Note that this permission check may not always make sense based on the directory provided; callers should consider using
validateFileMask(FilePath, String, boolean)and its overloads instead (once appropriate permission checks have succeeded).- Parameters:
value- The relative path being validated.errorIfNotExist- If true, report an error if the given relative path doesn't exist. Otherwise, it's a warning.expectingFile- If true, we expect the relative path to point to a file. Otherwise, the relative path is expected to be pointing to a directory.- Throws:
IOException
-
validateRelativeDirectory
public FormValidation validateRelativeDirectory(String value, boolean errorIfNotExist) throws IOException
A convenience method overvalidateRelativePath(String, boolean, boolean).- Throws:
IOException
-
validateRelativeDirectory
public FormValidation validateRelativeDirectory(String value) throws IOException
- Throws:
IOException
-
toString
@Deprecated public String toString()
Deprecated.
-
getChannel
public hudson.remoting.VirtualChannel getChannel()
-
isRemote
public boolean isRemote()
Returns true if thisFilePathrepresents a remote file.
-
getHomeDirectory
public static FilePath getHomeDirectory(hudson.remoting.VirtualChannel ch) throws InterruptedException, IOException
Gets theFilePathrepresentation of the "~" directory (User's home directory in the Unix sense) of the given channel.- Throws:
InterruptedExceptionIOException
-
ignoringSymlinks
public static FileVisitor ignoringSymlinks(FileVisitor v, String verificationRoot, OpenOption... openOptions)
WrapsFileVisitorto ignore symlinks.
-
ignoringTmpDirs
public static FileVisitor ignoringTmpDirs(FileVisitor v, String verificationRoot, OpenOption... openOptions)
WrapsFileVisitorto ignore tmp directories.
-
isDescendant
public boolean isDescendant(@NonNull String potentialChildRelativePath) throws IOException, InterruptedExceptionCheck if the relative child is really a descendant after symlink resolution if any.- Throws:
IOExceptionInterruptedException
-
-