Util.java 61.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * The MIT License
 *
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
K
kohsuke 已提交
24 25
package hudson;

K
kohsuke 已提交
26
import hudson.model.TaskListener;
27
import jenkins.util.MemoryReductionUtil;
K
kohsuke 已提交
28
import hudson.util.QuotedStringTokenizer;
K
kohsuke 已提交
29
import hudson.util.VariableResolver;
30
import jenkins.util.SystemProperties;
31

32
import jenkins.util.io.PathRemover;
33
import org.apache.commons.codec.digest.DigestUtils;
34
import org.apache.commons.io.IOUtils;
35
import org.apache.commons.io.output.NullOutputStream;
36
import org.apache.commons.lang.time.FastDateFormat;
K
kohsuke 已提交
37
import org.apache.tools.ant.BuildException;
38
import org.apache.tools.ant.Project;
K
kohsuke 已提交
39
import org.apache.tools.ant.taskdefs.Copy;
40
import org.apache.tools.ant.types.FileSet;
41

42 43 44
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

45
import java.io.*;
46 47
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
K
kohsuke 已提交
48
import java.net.InetAddress;
49 50
import java.net.URI;
import java.net.URISyntaxException;
51
import java.net.UnknownHostException;
52
import java.nio.ByteBuffer;
53 54
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
55
import java.nio.charset.Charset;
56
import java.nio.charset.CharsetEncoder;
57
import java.nio.charset.StandardCharsets;
58 59
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileSystemException;
60
import java.nio.file.FileSystems;
61
import java.nio.file.Files;
62
import java.nio.file.InvalidPathException;
63
import java.nio.file.LinkOption;
64 65
import java.nio.file.Path;
import java.nio.file.Paths;
66 67
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
68
import java.nio.file.attribute.PosixFilePermission;
69 70
import java.nio.file.attribute.PosixFilePermissions;
import java.security.DigestInputStream;
71 72
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
73 74
import java.text.NumberFormat;
import java.text.ParseException;
75 76
import java.time.LocalDate;
import java.time.ZoneId;
W
Wadeck Follonier 已提交
77
import java.time.temporal.ChronoUnit;
78
import java.util.*;
79
import java.util.concurrent.TimeUnit;
80
import java.util.concurrent.atomic.AtomicBoolean;
K
kohsuke 已提交
81
import java.util.logging.Level;
82
import java.util.logging.LogRecord;
K
kohsuke 已提交
83
import java.util.logging.Logger;
K
kohsuke 已提交
84 85 86
import java.util.regex.Matcher;
import java.util.regex.Pattern;

O
Oleg Nenashev 已提交
87 88
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
89
import javax.annotation.Nullable;
90 91
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
K
kohsuke 已提交
92

93
import org.apache.commons.io.FileUtils;
W
Wadeck Follonier 已提交
94
import org.kohsuke.stapler.StaplerRequest;
95

K
kohsuke 已提交
96
/**
K
kohsuke 已提交
97 98
 * Various utility methods that don't have more proper home.
 *
K
kohsuke 已提交
99 100 101
 * @author Kohsuke Kawaguchi
 */
public class Util {
K
kohsuke 已提交
102

103 104 105 106 107 108 109 110
    // Constant number of milliseconds in various time units.
    private static final long ONE_SECOND_MS = 1000;
    private static final long ONE_MINUTE_MS = 60 * ONE_SECOND_MS;
    private static final long ONE_HOUR_MS = 60 * ONE_MINUTE_MS;
    private static final long ONE_DAY_MS = 24 * ONE_HOUR_MS;
    private static final long ONE_MONTH_MS = 30 * ONE_DAY_MS;
    private static final long ONE_YEAR_MS = 365 * ONE_DAY_MS;

K
kohsuke 已提交
111 112
    /**
     * Creates a filtered sublist.
113
     * @since 1.176
K
kohsuke 已提交
114
     */
O
Oleg Nenashev 已提交
115 116
    @Nonnull
    public static <T> List<T> filter( @Nonnull Iterable<?> base, @Nonnull Class<T> type ) {
117
        List<T> r = new ArrayList<>();
K
kohsuke 已提交
118 119 120 121 122 123 124
        for (Object i : base) {
            if(type.isInstance(i))
                r.add(type.cast(i));
        }
        return r;
    }

125 126 127
    /**
     * Creates a filtered sublist.
     */
O
Oleg Nenashev 已提交
128 129
    @Nonnull
    public static <T> List<T> filter( @Nonnull List<?> base, @Nonnull Class<T> type ) {
130 131 132
        return filter((Iterable)base,type);
    }

133
    /**
134
     * Pattern for capturing variables. Either $xyz, ${xyz} or ${a.b} but not $a.b, while ignoring "$$"
135
      */
136
    private static final Pattern VARIABLE = Pattern.compile("\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_.]+\\}|\\$)");
137

K
kohsuke 已提交
138
    /**
139
     * Replaces the occurrence of '$key' by {@code properties.get('key')}.
K
kohsuke 已提交
140 141
     *
     * <p>
142
     * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
143
     *
K
kohsuke 已提交
144
     */
145
    @Nullable
O
Oleg Nenashev 已提交
146
    public static String replaceMacro( @CheckForNull String s, @Nonnull Map<String,String> properties) {
147
        return replaceMacro(s, new VariableResolver.ByMap<>(properties));
K
kohsuke 已提交
148
    }
149

K
kohsuke 已提交
150
    /**
151
     * Replaces the occurrence of '$key' by {@code resolver.get('key')}.
K
kohsuke 已提交
152 153 154 155
     *
     * <p>
     * Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
     */
156
    @Nullable
O
Oleg Nenashev 已提交
157
    public static String replaceMacro(@CheckForNull String s, @Nonnull VariableResolver<String> resolver) {
158 159 160
    	if (s == null) {
    		return null;
    	}
161

K
kohsuke 已提交
162
        int idx=0;
163 164 165 166 167 168
        while(true) {
            Matcher m = VARIABLE.matcher(s);
            if(!m.find(idx))   return s;

            String key = m.group().substring(1);

169 170 171 172 173 174 175 176 177
            // escape the dollar sign or get the key to resolve
            String value;
            if(key.charAt(0)=='$') {
               value = "$";
            } else {
               if(key.charAt(0)=='{')  key = key.substring(1,key.length()-1);
               value = resolver.resolve(key);
            }

178
            if(value==null)
179
                idx = m.end(); // skip this
180 181
            else {
                s = s.substring(0,m.start())+value+s.substring(m.end());
182
                idx = m.start() + value.length();
K
kohsuke 已提交
183 184 185 186
            }
        }
    }

K
kohsuke 已提交
187
    /**
188 189 190 191 192 193 194 195 196
     * Reads the entire contents of the text file at <code>logfile</code> into a
     * string using the {@link Charset#defaultCharset() default charset} for
     * decoding. If no such file exists, an empty string is returned.
     * @param logfile The text file to read in its entirety.
     * @return The entire text content of <code>logfile</code>.
     * @throws IOException If an error occurs while reading the file.
     * @deprecated call {@link #loadFile(java.io.File, java.nio.charset.Charset)}
     * instead to specify the charset to use for decoding (preferably
     * {@link java.nio.charset.StandardCharsets#UTF_8}).
K
kohsuke 已提交
197
     */
O
Oleg Nenashev 已提交
198
    @Nonnull
199
    @Deprecated
O
Oleg Nenashev 已提交
200
    public static String loadFile(@Nonnull File logfile) throws IOException {
201 202 203
        return loadFile(logfile, Charset.defaultCharset());
    }

204 205 206 207 208 209 210 211 212
    /**
     * Reads the entire contents of the text file at <code>logfile</code> into a
     * string using <code>charset</code> for decoding. If no such file exists,
     * an empty string is returned.
     * @param logfile The text file to read in its entirety.
     * @param charset The charset to use for decoding the bytes in <code>logfile</code>.
     * @return The entire text content of <code>logfile</code>.
     * @throws IOException If an error occurs while reading the file.
     */
O
Oleg Nenashev 已提交
213 214
    @Nonnull
    public static String loadFile(@Nonnull File logfile, @Nonnull Charset charset) throws IOException {
215 216 217 218 219 220 221
        // Note: Until charset handling is resolved (e.g. by implementing
        // https://issues.jenkins-ci.org/browse/JENKINS-48923 ), this method
        // must be able to handle character encoding errors. As reported at
        // https://issues.jenkins-ci.org/browse/JENKINS-49112 Run.getLog() calls
        // loadFile() to fully read the generated log file. This file might
        // contain unmappable and/or malformed byte sequences. We need to make
        // sure that in such cases, no CharacterCodingException is thrown.
222
        //
223 224 225 226 227 228 229 230 231 232
        // One approach that cannot be used is to call Files.newBufferedReader()
        // because there is a difference in how an InputStreamReader constructed
        // from a Charset and the reader returned by Files.newBufferedReader()
        // handle malformed and unmappable byte sequences for the specified
        // encoding; the latter is more picky and will throw an exception.
        // See: https://issues.jenkins-ci.org/browse/JENKINS-49060?focusedCommentId=325989&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-325989
        try {
            return FileUtils.readFileToString(logfile, charset);
        } catch (FileNotFoundException e) {
            return "";
233
        } catch (Exception e) {
234
            throw new IOException("Failed to fully read " + logfile, e);
235
        }
K
kohsuke 已提交
236 237 238 239 240
    }

    /**
     * Deletes the contents of the given directory (but not the directory itself)
     * recursively.
241 242
     * It does not take no for an answer - if necessary, it will have multiple
     * attempts at deleting things.
K
kohsuke 已提交
243 244 245 246
     *
     * @throws IOException
     *      if the operation fails.
     */
O
Oleg Nenashev 已提交
247
    public static void deleteContentsRecursive(@Nonnull File file) throws IOException {
248
        deleteContentsRecursive(fileToPath(file), PathRemover.PathChecker.ALLOW_ALL);
249 250 251
    }

    /**
252
     * Deletes the given directory contents (but not the directory itself) recursively using a PathChecker.
253
     * @param path a directory to delete
254
     * @param pathChecker a security check to validate a path before deleting
255 256 257
     * @throws IOException if the operation fails
     */
    @Restricted(NoExternalUse.class)
258 259
    public static void deleteContentsRecursive(@Nonnull Path path, @Nonnull PathRemover.PathChecker pathChecker) throws IOException {
        newPathRemover(pathChecker).forceRemoveDirectoryContents(path);
K
kohsuke 已提交
260 261
    }

262 263
    /**
     * Deletes this file (and does not take no for an answer).
264 265
     * If necessary, it will have multiple attempts at deleting things.
     *
266 267 268
     * @param f a file to delete
     * @throws IOException if it exists but could not be successfully deleted
     */
O
Oleg Nenashev 已提交
269
    public static void deleteFile(@Nonnull File f) throws IOException {
270
        newPathRemover(PathRemover.PathChecker.ALLOW_ALL).forceRemoveFile(fileToPath(f));
271 272
    }

273 274 275 276 277 278 279 280
    /**
     * Deletes the given directory (including its contents) recursively.
     * It does not take no for an answer - if necessary, it will have multiple
     * attempts at deleting things.
     *
     * @throws IOException
     * if the operation fails.
     */
O
Oleg Nenashev 已提交
281
    public static void deleteRecursive(@Nonnull File dir) throws IOException {
282
        deleteRecursive(fileToPath(dir), PathRemover.PathChecker.ALLOW_ALL);
283 284 285
    }

    /**
286 287
     * Deletes the given directory and contents recursively using a filter.
     * @param dir a directory to delete
288
     * @param pathChecker a security check to validate a path before deleting
289
     * @throws IOException if the operation fails
290
     */
291
    @Restricted(NoExternalUse.class)
292 293
    public static void deleteRecursive(@Nonnull Path dir, @Nonnull PathRemover.PathChecker pathChecker) throws IOException {
        newPathRemover(pathChecker).forceRemoveRecursive(dir);
K
kohsuke 已提交
294 295
    }

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    /*
     * Copyright 2001-2004 The Apache Software Foundation.
     *
     * Licensed 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.
     */
    /**
M
Matt Sicker 已提交
312 313 314
     * Checks if the given file represents a symlink. Unlike {@link Files#isSymbolicLink(Path)}, this method also
     * considers <a href="https://en.wikipedia.org/wiki/NTFS_junction_point">NTFS junction points</a> as symbolic
     * links.
315
     */
O
Oleg Nenashev 已提交
316
    public static boolean isSymlink(@Nonnull File file) throws IOException {
317 318 319 320 321
        return isSymlink(fileToPath(file));
    }

    @Restricted(NoExternalUse.class)
    public static boolean isSymlink(@Nonnull Path path) {
322
        /*
323 324 325 326 327 328 329 330 331 332
         *  Windows Directory Junctions are effectively the same as Linux symlinks to directories.
         *  Unfortunately, the Java 7 NIO2 API function isSymbolicLink does not treat them as such.
         *  It thinks of them as normal directories.  To use the NIO2 API & treat it like a symlink,
         *  you have to go through BasicFileAttributes and do the following check:
         *     isSymbolicLink() || isOther()
         *  The isOther() call will include Windows reparse points, of which a directory junction is.
         *  It also includes includes devices, but reading the attributes of a device with NIO fails
         *  or returns false for isOther(). (i.e. named pipes such as \\.\pipe\JenkinsTestPipe return
         *  false for isOther(), and drives such as \\.\PhysicalDrive0 throw an exception when
         *  calling readAttributes.
333
         */
334
        try {
335
            BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
M
Matt Sicker 已提交
336
            return attrs.isSymbolicLink() || (attrs instanceof DosFileAttributes && attrs.isOther());
M
Matt Sicker 已提交
337
        } catch (IOException ignored) {
338
            return false;
339 340 341
        }
    }

342 343 344 345 346 347
    /**
     * A mostly accurate check of whether a path is a relative path or not. This is designed to take a path against
     * an unknown operating system so may give invalid results.
     *
     * @param path the path.
     * @return {@code true} if the path looks relative.
348
     * @since 1.606
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
     */
    public static boolean isRelativePath(String path) {
        if (path.startsWith("/"))
            return false;
        if (path.startsWith("\\\\") && path.length() > 3 && path.indexOf('\\', 3) != -1)
            return false; // a UNC path which is the most absolute you can get on windows
        if (path.length() >= 3 && ':' == path.charAt(1)) {
            // never mind that the drive mappings can be changed between sessions, we just want to
            // know if the 3rd character is a `\` (or a '/' is acceptable too)
            char p = path.charAt(0);
            if (('A' <= p && p <= 'Z') || ('a' <= p && p <= 'z')) {
                return path.charAt(2) != '\\' && path.charAt(2) != '/';
            }
        }
        return true;
    }

366 367 368 369 370 371
    /**
     * A check if a file path is a descendant of a parent path
     * @param forParent the parent the child should be a descendant of
     * @param potentialChild the path to check
     * @return true if so
     * @throws IOException for invalid paths
372
     * @since 2.80
373 374 375
     * @see InvalidPathException
     */
    public static boolean isDescendant(File forParent, File potentialChild) throws IOException {
376 377 378
        Path child = fileToPath(potentialChild.getAbsoluteFile()).normalize();
        Path parent = fileToPath(forParent.getAbsoluteFile()).normalize();
        return child.startsWith(parent);
379 380
    }

K
kohsuke 已提交
381 382 383 384
    /**
     * Creates a new temporary directory.
     */
    public static File createTempDir() throws IOException {
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
        // The previously used approach of creating a temporary file, deleting
        // it, and making a new directory having the same name in its place is
        // potentially  problematic:
        // https://stackoverflow.com/questions/617414/how-to-create-a-temporary-directory-folder-in-java
        // We can use the Java 7 Files.createTempDirectory() API, but note that
        // by default, the permissions of the created directory are 0700&(~umask)
        // whereas the old approach created a temporary directory with permissions
        // 0777&(~umask).
        // To avoid permissions problems like https://issues.jenkins-ci.org/browse/JENKINS-48407
        // we can pass POSIX file permissions as an attribute (see, for example,
        // https://github.com/jenkinsci/jenkins/pull/3161 )
        final Path tempPath;
        final String tempDirNamePrefix = "jenkins";
        if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) {
            tempPath = Files.createTempDirectory(tempDirNamePrefix,
                    PosixFilePermissions.asFileAttribute(EnumSet.allOf(PosixFilePermission.class)));
        } else {
            tempPath = Files.createTempDirectory(tempDirNamePrefix);
        }
        return tempPath.toFile();
K
kohsuke 已提交
405 406
    }

407
    private static final Pattern errorCodeParser = Pattern.compile(".*CreateProcess.*error=([0-9]+).*");
K
kohsuke 已提交
408 409 410 411 412

    /**
     * On Windows, error messages for IOException aren't very helpful.
     * This method generates additional user-friendly error message to the listener
     */
O
Oleg Nenashev 已提交
413
    public static void displayIOException(@Nonnull IOException e, @Nonnull TaskListener listener ) {
K
kohsuke 已提交
414 415 416 417 418
        String msg = getWin32ErrorMessage(e);
        if(msg!=null)
            listener.getLogger().println(msg);
    }

O
Oleg Nenashev 已提交
419 420
    @CheckForNull
    public static String getWin32ErrorMessage(@Nonnull IOException e) {
421 422 423
        return getWin32ErrorMessage((Throwable)e);
    }

K
kohsuke 已提交
424
    /**
425
     * Extracts the Win32 error message from {@link Throwable} if possible.
K
kohsuke 已提交
426 427 428 429
     *
     * @return
     *      null if there seems to be no error code or if the platform is not Win32.
     */
O
Oleg Nenashev 已提交
430
    @CheckForNull
431
    public static String getWin32ErrorMessage(Throwable e) {
K
kohsuke 已提交
432
        String msg = e.getMessage();
433 434 435 436 437 438
        if(msg!=null) {
            Matcher m = errorCodeParser.matcher(msg);
            if(m.matches()) {
                try {
                    ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
                    return rb.getString("error"+m.group(1));
439
                } catch (Exception ignored) {
440 441 442
                    // silently recover from resource related failures
                }
            }
443
        }
K
kohsuke 已提交
444

445 446 447
        if(e.getCause()!=null)
            return getWin32ErrorMessage(e.getCause());
        return null; // no message
K
kohsuke 已提交
448 449
    }

450
    /**
451
     * Gets a human readable message for the given Win32 error code.
452 453 454 455
     *
     * @return
     *      null if no such message is available.
     */
O
Oleg Nenashev 已提交
456
    @CheckForNull
457
    public static String getWin32ErrorMessage(int n) {
458 459 460 461 462 463 464
        try {
            ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
            return rb.getString("error"+n);
        } catch (MissingResourceException e) {
            LOGGER.log(Level.WARNING,"Failed to find resource bundle",e);
            return null;
        }
465 466
    }

K
kohsuke 已提交
467 468 469
    /**
     * Guesses the current host name.
     */
O
Oleg Nenashev 已提交
470
    @Nonnull
K
kohsuke 已提交
471 472 473 474 475 476 477 478
    public static String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "localhost";
        }
    }

479 480 481 482
    /**
     * @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)}
     */
    @Deprecated
O
Oleg Nenashev 已提交
483
    public static void copyStream(@Nonnull InputStream in,@Nonnull OutputStream out) throws IOException {
484
        IOUtils.copy(in, out);
K
kohsuke 已提交
485 486
    }

487 488 489 490
    /**
     * @deprecated Use {@link IOUtils#copy(Reader, Writer)}
     */
    @Deprecated
O
Oleg Nenashev 已提交
491
    public static void copyStream(@Nonnull Reader in, @Nonnull Writer out) throws IOException {
492
        IOUtils.copy(in, out);
K
kohsuke 已提交
493 494
    }

495 496 497 498
    /**
     * @deprecated Use {@link IOUtils#copy(InputStream, OutputStream)} in a {@code try}-with-resources block
     */
    @Deprecated
O
Oleg Nenashev 已提交
499
    public static void copyStreamAndClose(@Nonnull InputStream in, @Nonnull OutputStream out) throws IOException {
500
        try (InputStream _in = in; OutputStream _out = out) { // make sure both are closed, and use Throwable.addSuppressed
501
            IOUtils.copy(_in, _out);
K
kohsuke 已提交
502 503 504
        }
    }

505 506 507 508
    /**
     * @deprecated Use {@link IOUtils#copy(Reader, Writer)} in a {@code try}-with-resources block
     */
    @Deprecated
O
Oleg Nenashev 已提交
509
    public static void copyStreamAndClose(@Nonnull Reader in, @Nonnull Writer out) throws IOException {
510
        try (Reader _in = in; Writer _out = out) {
511
            IOUtils.copy(_in, _out);
K
kohsuke 已提交
512 513 514
        }
    }

K
kohsuke 已提交
515
    /**
K
kohsuke 已提交
516 517 518 519 520 521
     * Tokenizes the text separated by delimiters.
     *
     * <p>
     * In 1.210, this method was changed to handle quotes like Unix shell does.
     * Before that, this method just used {@link StringTokenizer}.
     *
K
kohsuke 已提交
522
     * @since 1.145
K
kohsuke 已提交
523
     * @see QuotedStringTokenizer
K
kohsuke 已提交
524
     */
O
Oleg Nenashev 已提交
525 526
    @Nonnull
    public static String[] tokenize(@Nonnull String s, @CheckForNull String delimiter) {
K
kohsuke 已提交
527
        return QuotedStringTokenizer.tokenize(s,delimiter);
K
kohsuke 已提交
528 529
    }

O
Oleg Nenashev 已提交
530 531
    @Nonnull
    public static String[] tokenize(@Nonnull String s) {
K
kohsuke 已提交
532 533 534
        return tokenize(s," \t\n\r\f");
    }

535 536 537
    /**
     * Converts the map format of the environment variables to the K=V format in the array.
     */
O
Oleg Nenashev 已提交
538 539
    @Nonnull
    public static String[] mapToEnv(@Nonnull Map<String,String> m) {
K
kohsuke 已提交
540 541 542
        String[] r = new String[m.size()];
        int idx=0;

J
jglick 已提交
543 544
        for (final Map.Entry<String,String> e : m.entrySet()) {
            r[idx++] = e.getKey() + '=' + e.getValue();
K
kohsuke 已提交
545 546 547 548
        }
        return r;
    }

O
Oleg Nenashev 已提交
549
    public static int min(int x, @Nonnull int... values) {
K
kohsuke 已提交
550 551 552 553 554 555 556
        for (int i : values) {
            if(i<x)
                x=i;
        }
        return x;
    }

O
Oleg Nenashev 已提交
557 558
    @CheckForNull
    public static String nullify(@CheckForNull String v) {
K
Kohsuke Kawaguchi 已提交
559
        return fixEmpty(v);
K
kohsuke 已提交
560 561
    }

O
Oleg Nenashev 已提交
562 563
    @Nonnull
    public static String removeTrailingSlash(@Nonnull String s) {
K
kohsuke 已提交
564 565 566 567
        if(s.endsWith("/")) return s.substring(0,s.length()-1);
        else                return s;
    }

K
Kohsuke Kawaguchi 已提交
568 569 570 571 572 573 574 575 576 577

    /**
     * Ensure string ends with suffix
     *
     * @param subject Examined string
     * @param suffix  Desired suffix
     * @return Original subject in case it already ends with suffix, null in
     *         case subject was null and subject + suffix otherwise.
     * @since 1.505
     */
578
    @Nullable
O
Oleg Nenashev 已提交
579
    public static String ensureEndsWith(@CheckForNull String subject, @CheckForNull String suffix) {
K
Kohsuke Kawaguchi 已提交
580 581 582 583 584 585 586 587

        if (subject == null) return null;

        if (subject.endsWith(suffix)) return subject;

        return subject + suffix;
    }

K
kohsuke 已提交
588 589 590 591 592
    /**
     * Computes MD5 digest of the given input stream.
     *
     * @param source
     *      The stream will be closed by this method at the end of this method.
K
kohsuke 已提交
593 594
     * @return
     *      32-char wide string
J
Jesse Glick 已提交
595
     * @see DigestUtils#md5Hex(InputStream)
K
kohsuke 已提交
596
     */
O
Oleg Nenashev 已提交
597 598
    @Nonnull
    public static String getDigestOf(@Nonnull InputStream source) throws IOException {
599 600
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
601 602 603 604
            DigestInputStream in = new DigestInputStream(source, md5);
            // Note: IOUtils.copy() buffers the input internally, so there is no
            // need to use a BufferedInputStream.
            IOUtils.copy(in, NullOutputStream.NULL_OUTPUT_STREAM);
605 606
            return toHexString(md5.digest());
        } catch (NoSuchAlgorithmException e) {
607
            throw new IOException("MD5 not installed",e);    // impossible
608 609
        } finally {
            source.close();
610 611
        }
        /* JENKINS-18178: confuses Maven 2 runner
612 613 614 615 616
        try {
            return DigestUtils.md5Hex(source);
        } finally {
            source.close();
        }
617
        */
K
kohsuke 已提交
618
    }
619

O
Oleg Nenashev 已提交
620 621
    @Nonnull
    public static String getDigestOf(@Nonnull String text) {
622
        try {
623
            return getDigestOf(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));
624 625 626 627
        } catch (IOException e) {
            throw new Error(e);
        }
    }
K
kohsuke 已提交
628

629 630 631 632 633 634 635
    /**
     * Computes the MD5 digest of a file.
     * @param file a file
     * @return a 32-character string
     * @throws IOException in case reading fails
     * @since 1.525
     */
O
Oleg Nenashev 已提交
636 637
    @Nonnull
    public static String getDigestOf(@Nonnull File file) throws IOException {
638 639
        // Note: getDigestOf() closes the input stream.
        return getDigestOf(Files.newInputStream(fileToPath(file)));
640 641
    }

642
    /**
643
     * Converts a string into 128-bit AES key.
644 645
     * @since 1.308
     */
646
    @Nonnull
O
Oleg Nenashev 已提交
647
    public static SecretKey toAes128Key(@Nonnull String s) {
648 649 650 651
        try {
            // turn secretKey into 256 bit hash
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            digest.reset();
652
            digest.update(s.getBytes(StandardCharsets.UTF_8));
653 654 655 656 657 658 659 660

            // Due to the stupid US export restriction JDK only ships 128bit version.
            return new SecretKeySpec(digest.digest(),0,128/8, "AES");
        } catch (NoSuchAlgorithmException e) {
            throw new Error(e);
        }
    }

O
Oleg Nenashev 已提交
661 662
    @Nonnull
    public static String toHexString(@Nonnull byte[] data, int start, int len) {
663
        StringBuilder buf = new StringBuilder();
K
kohsuke 已提交
664 665 666 667 668 669 670 671
        for( int i=0; i<len; i++ ) {
            int b = data[start+i]&0xFF;
            if(b<16)    buf.append('0');
            buf.append(Integer.toHexString(b));
        }
        return buf.toString();
    }

O
Oleg Nenashev 已提交
672 673
    @Nonnull
    public static String toHexString(@Nonnull byte[] bytes) {
K
kohsuke 已提交
674 675 676
        return toHexString(bytes,0,bytes.length);
    }

O
Oleg Nenashev 已提交
677 678
    @Nonnull
    public static byte[] fromHexString(@Nonnull String data) {
679 680
        if (data.length() % 2 != 0)
            throw new IllegalArgumentException("data must have an even number of hexadecimal digits");
K
kohsuke 已提交
681 682 683 684 685 686
        byte[] r = new byte[data.length() / 2];
        for (int i = 0; i < data.length(); i += 2)
            r[i / 2] = (byte) Integer.parseInt(data.substring(i, i + 2), 16);
        return r;
    }

K
kohsuke 已提交
687
    /**
K
kohsuke 已提交
688
     * Returns a human readable text of the time duration, for example "3 minutes 40 seconds".
K
i18n  
kohsuke 已提交
689
     * This version should be used for representing a duration of some activity (like build)
K
kohsuke 已提交
690 691 692 693
     *
     * @param duration
     *      number of milliseconds.
     */
O
Oleg Nenashev 已提交
694
    @Nonnull
K
kohsuke 已提交
695
    public static String getTimeSpanString(long duration) {
696 697 698 699 700 701 702 703 704 705 706 707
        // Break the duration up in to units.
        long years = duration / ONE_YEAR_MS;
        duration %= ONE_YEAR_MS;
        long months = duration / ONE_MONTH_MS;
        duration %= ONE_MONTH_MS;
        long days = duration / ONE_DAY_MS;
        duration %= ONE_DAY_MS;
        long hours = duration / ONE_HOUR_MS;
        duration %= ONE_HOUR_MS;
        long minutes = duration / ONE_MINUTE_MS;
        duration %= ONE_MINUTE_MS;
        long seconds = duration / ONE_SECOND_MS;
708 709
        duration %= ONE_SECOND_MS;
        long millisecs = duration;
710 711

        if (years > 0)
C
cactusman 已提交
712
            return makeTimeSpanString(years, Messages.Util_year(years), months, Messages.Util_month(months));
713
        else if (months > 0)
C
cactusman 已提交
714
            return makeTimeSpanString(months, Messages.Util_month(months), days, Messages.Util_day(days));
715
        else if (days > 0)
C
cactusman 已提交
716
            return makeTimeSpanString(days, Messages.Util_day(days), hours, Messages.Util_hour(hours));
717
        else if (hours > 0)
C
cactusman 已提交
718
            return makeTimeSpanString(hours, Messages.Util_hour(hours), minutes, Messages.Util_minute(minutes));
719
        else if (minutes > 0)
C
cactusman 已提交
720
            return makeTimeSpanString(minutes, Messages.Util_minute(minutes), seconds, Messages.Util_second(seconds));
721
        else if (seconds >= 10)
C
cactusman 已提交
722
            return Messages.Util_second(seconds);
723
        else if (seconds >= 1)
724
            return Messages.Util_second(seconds+(float)(millisecs/100)/10); // render "1.2 sec"
725
        else if(millisecs>=100)
726
            return Messages.Util_second((float)(millisecs/10)/100); // render "0.12 sec".
727 728
        else
            return Messages.Util_millisecond(millisecs);
K
kohsuke 已提交
729 730
    }

731 732

    /**
733
     * Create a string representation of a time duration.  If the quantity of
734
     * the most significant unit is big (>=10), then we use only that most
735
     * significant unit in the string representation. If the quantity of the
736 737 738 739 740
     * most significant unit is small (a single-digit value), then we also
     * use a secondary, smaller unit for increased precision.
     * So 13 minutes and 43 seconds returns just "13 minutes", but 3 minutes
     * and 43 seconds is "3 minutes 43 seconds".
     */
O
Oleg Nenashev 已提交
741
    @Nonnull
742
    private static String makeTimeSpanString(long bigUnit,
O
Oleg Nenashev 已提交
743
                                             @Nonnull String bigLabel,
744
                                             long smallUnit,
O
Oleg Nenashev 已提交
745
                                             @Nonnull String smallLabel) {
C
cactusman 已提交
746
        String text = bigLabel;
747
        if (bigUnit < 10)
C
cactusman 已提交
748
            text += ' ' + smallLabel;
749 750 751 752
        return text;
    }


K
i18n  
kohsuke 已提交
753 754
    /**
     * Get a human readable string representing strings like "xxx days ago",
755
     * which should be used to point to the occurrence of an event in the past.
K
i18n  
kohsuke 已提交
756
     */
O
Oleg Nenashev 已提交
757
    @Nonnull
K
i18n  
kohsuke 已提交
758 759 760 761
    public static String getPastTimeString(long duration) {
        return Messages.Util_pastTime(getTimeSpanString(duration));
    }

762

K
kohsuke 已提交
763
    /**
K
kohsuke 已提交
764
     * Combines number and unit, with a plural suffix if needed.
765 766 767
     *
     * @deprecated
     *   Use individual localization methods instead.
768
     *   See {@link Messages#Util_year(Object)} for an example.
769
     *   Deprecated since 2009-06-24, remove method after 2009-12-24.
K
kohsuke 已提交
770
     */
O
Oleg Nenashev 已提交
771
    @Nonnull
772
    @Deprecated
O
Oleg Nenashev 已提交
773
    public static String combine(long n, @Nonnull String suffix) {
K
kohsuke 已提交
774 775
        String s = Long.toString(n)+' '+suffix;
        if(n!=1)
776 777
        	// Just adding an 's' won't work in most natural languages, even English has exception to the rule (e.g. copy/copies).
            s += "s";
K
kohsuke 已提交
778 779 780
        return s;
    }

K
kohsuke 已提交
781 782 783
    /**
     * Create a sub-list by only picking up instances of the specified type.
     */
O
Oleg Nenashev 已提交
784 785
    @Nonnull
    public static <T> List<T> createSubList(@Nonnull Collection<?> source, @Nonnull Class<T> type ) {
786
        List<T> r = new ArrayList<>();
K
kohsuke 已提交
787 788 789 790 791 792 793
        for (Object item : source) {
            if(type.isInstance(item))
                r.add(type.cast(item));
        }
        return r;
    }

K
kohsuke 已提交
794
    /**
K
kohsuke 已提交
795
     * Escapes non-ASCII characters in URL.
796 797 798 799 800
     *
     * <p>
     * Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters,
     * such as '#'.
     * {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
801
     * a single path component to that method (it will encode /, but this method does not).
K
kohsuke 已提交
802
     */
803
    @Nonnull
O
Oleg Nenashev 已提交
804
    public static String encode(@Nonnull String s) {
K
kohsuke 已提交
805 806 807
        try {
            boolean escaped = false;

808
            StringBuilder out = new StringBuilder(s.length());
K
kohsuke 已提交
809 810

            ByteArrayOutputStream buf = new ByteArrayOutputStream();
811
            OutputStreamWriter w = new OutputStreamWriter(buf, StandardCharsets.UTF_8);
K
kohsuke 已提交
812 813

            for (int i = 0; i < s.length(); i++) {
814
                int c = s.charAt(i);
L
lvotypko 已提交
815
                if (c<128 && c!=' ') {
K
kohsuke 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
                    out.append((char) c);
                } else {
                    // 1 char -> UTF8
                    w.write(c);
                    w.flush();
                    for (byte b : buf.toByteArray()) {
                        out.append('%');
                        out.append(toDigit((b >> 4) & 0xF));
                        out.append(toDigit(b & 0xF));
                    }
                    buf.reset();
                    escaped = true;
                }
            }

            return escaped ? out.toString() : s;
        } catch (IOException e) {
            throw new Error(e); // impossible
        }
    }

837 838 839
    private static final boolean[] uriMap = new boolean[123];
    static {
        String raw =
840 841
    "!  $ &'()*+,-. 0123456789   =  @ABCDEFGHIJKLMNOPQRSTUVWXYZ    _ abcdefghijklmnopqrstuvwxyz";
  //  "# %         /          :;< >?                           [\]^ `                          {|}~
842 843 844 845 846
  //  ^--so these are encoded
        int i;
        // Encode control chars and space
        for (i = 0; i < 33; i++) uriMap[i] = true;
        for (int j = 0; j < raw.length(); i++, j++)
847
            uriMap[i] = (raw.charAt(j) == ' ');
848 849 850 851
        // If we add encodeQuery() just add a 2nd map to encode &+=
        // queryMap[38] = queryMap[43] = queryMap[61] = true;
    }

852 853
    /**
     * Encode a single path component for use in an HTTP URL.
J
Jesse Glick 已提交
854 855 856 857
     * Escapes all non-ASCII, general unsafe (space and {@code "#%<>[\]^`{|}~})
     * and HTTP special characters ({@code /;:?}) as specified in RFC1738.
     * (so alphanumeric and {@code !@$&*()-_=+',.} are not encoded)
     * Note that slash ({@code /}) is encoded, so the given string should be a
858
     * single path component used in constructing a URL.
859
     * Method name inspired by PHP's rawurlencode.
860
     */
O
Oleg Nenashev 已提交
861 862
    @Nonnull
    public static String rawEncode(@Nonnull String s) {
863 864 865 866 867 868
        boolean escaped = false;
        StringBuilder out = null;
        CharsetEncoder enc = null;
        CharBuffer buf = null;
        char c;
        for (int i = 0, m = s.length(); i < m; i++) {
A
Alex Earl 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
            int codePoint = Character.codePointAt(s, i);
            if((codePoint&0xffffff80)==0) { // 1 byte
                c = s.charAt(i);
                if (c > 122 || uriMap[c]) {
                    if (!escaped) {
                        out = new StringBuilder(i + (m - i) * 3);
                        out.append(s, 0, i);
                        enc = StandardCharsets.UTF_8.newEncoder();
                        buf = CharBuffer.allocate(1);
                        escaped = true;
                    }
                    // 1 char -> UTF8
                    buf.put(0, c);
                    buf.rewind();
                    try {
                        ByteBuffer bytes = enc.encode(buf);
                        while (bytes.hasRemaining()) {
                            byte b = bytes.get();
                            out.append('%');
                            out.append(toDigit((b >> 4) & 0xF));
                            out.append(toDigit(b & 0xF));
                        }
                    } catch (CharacterCodingException ex) {
                    }
                } else if (escaped) {
                    out.append(c);
                }
            } else {
897 898
                if (!escaped) {
                    out = new StringBuilder(i + (m - i) * 3);
899
                    out.append(s, 0, i);
900 901
                    escaped = true;
                }
A
Alex Earl 已提交
902 903 904 905 906 907 908 909 910 911 912

                byte[] bytes = new String(new int[] { codePoint }, 0, 1).getBytes(StandardCharsets.UTF_8);
                for(int j=0;j<bytes.length;j++) {
                    out.append('%');
                    out.append(toDigit((bytes[j] >> 4) & 0xF));
                    out.append(toDigit(bytes[j] & 0xF));
                }

                if(Character.charCount(codePoint) > 1) {
                    i++; // we processed two characters
                }
913 914 915 916 917 918 919 920 921
            }
        }
        return escaped ? out.toString() : s;
    }

    private static char toDigit(int n) {
        return (char)(n < 10 ? '0' + n : 'A' + n - 10);
    }

K
kohsuke 已提交
922 923 924 925 926 927 928
    /**
     * Surrounds by a single-quote.
     */
    public static String singleQuote(String s) {
        return '\''+s+'\'';
    }

929
    /**
930
     * Escapes HTML unsafe characters like &lt;, &amp; to the respective character entities.
931
     */
932 933
    @Nullable
    public static String escape(@CheckForNull String text) {
K
kohsuke 已提交
934
        if (text==null)     return null;
935
        StringBuilder buf = new StringBuilder(text.length()+64);
936 937 938 939 940 941 942 943
        for( int i=0; i<text.length(); i++ ) {
            char ch = text.charAt(i);
            if(ch=='\n')
                buf.append("<br>");
            else
            if(ch=='<')
                buf.append("&lt;");
            else
944 945 946
            if(ch=='>')
                buf.append("&gt;");
            else
947 948 949
            if(ch=='&')
                buf.append("&amp;");
            else
S
Seiji Sogabe 已提交
950 951 952 953 954 955
            if(ch=='"')
                buf.append("&quot;");
            else
            if(ch=='\'')
                buf.append("&#039;");
            else
956 957 958 959 960 961 962 963
            if(ch==' ') {
                // All spaces in a block of consecutive spaces are converted to
                // non-breaking space (&nbsp;) except for the last one.  This allows
                // significant whitespace to be retained without prohibiting wrapping.
                char nextCh = i+1 < text.length() ? text.charAt(i+1) : 0;
                buf.append(nextCh==' ' ? "&nbsp;" : " ");
            }
            else
964 965 966 967 968
                buf.append(ch);
        }
        return buf.toString();
    }

O
Oleg Nenashev 已提交
969 970
    @Nonnull
    public static String xmlEscape(@Nonnull String text) {
971
        StringBuilder buf = new StringBuilder(text.length()+64);
K
kohsuke 已提交
972 973 974 975 976
        for( int i=0; i<text.length(); i++ ) {
            char ch = text.charAt(i);
            if(ch=='<')
                buf.append("&lt;");
            else
977 978 979
            if(ch=='>')
                buf.append("&gt;");
            else
K
kohsuke 已提交
980 981 982 983 984 985 986 987
            if(ch=='&')
                buf.append("&amp;");
            else
                buf.append(ch);
        }
        return buf.toString();
    }

K
kohsuke 已提交
988
    /**
989 990 991 992
     * Creates an empty file if nonexistent or truncates the existing file.
     * Note: The behavior of this method in the case where the file already
     * exists is unlike the POSIX <code>touch</code> utility which merely
     * updates the file's access and/or modification time.
K
kohsuke 已提交
993
     */
O
Oleg Nenashev 已提交
994
    public static void touch(@Nonnull File file) throws IOException {
995
        Files.newOutputStream(fileToPath(file)).close();
K
kohsuke 已提交
996 997 998 999 1000
    }

    /**
     * Copies a single file by using Ant.
     */
O
Oleg Nenashev 已提交
1001
    public static void copyFile(@Nonnull File src, @Nonnull File dst) throws BuildException {
K
kohsuke 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
        Copy cp = new Copy();
        cp.setProject(new org.apache.tools.ant.Project());
        cp.setTofile(dst);
        cp.setFile(src);
        cp.setOverwrite(true);
        cp.execute();
    }

    /**
     * Convert null to "".
     */
O
Oleg Nenashev 已提交
1013 1014
    @Nonnull
    public static String fixNull(@CheckForNull String s) {
1015 1016 1017 1018
        return fixNull(s, "");
    }

    /**
O
Oleg Nenashev 已提交
1019 1020
     * Convert {@code null} to a default value.
     * @param defaultValue Default value. It may be immutable or not, depending on the implementation.
1021
     * @since 2.144
1022
     */
1023 1024
    @Nonnull
    public static <T> T fixNull(@CheckForNull T s, @Nonnull T defaultValue) {
1025
        return s != null ? s : defaultValue;
K
kohsuke 已提交
1026 1027 1028 1029 1030
    }

    /**
     * Convert empty string to null.
     */
O
Oleg Nenashev 已提交
1031 1032
    @CheckForNull
    public static String fixEmpty(@CheckForNull String s) {
K
kohsuke 已提交
1033 1034 1035 1036
        if(s==null || s.length()==0)    return null;
        return s;
    }

K
kohsuke 已提交
1037 1038 1039 1040 1041
    /**
     * Convert empty string to null, and trim whitespace.
     *
     * @since 1.154
     */
O
Oleg Nenashev 已提交
1042 1043
    @CheckForNull
    public static String fixEmptyAndTrim(@CheckForNull String s) {
K
kohsuke 已提交
1044
        if(s==null)    return null;
K
kohsuke 已提交
1045
        return fixEmpty(s.trim());
K
kohsuke 已提交
1046 1047
    }

1048 1049
    /**
     *
O
Olivier Truong 已提交
1050
     * @param l list to check.
1051
     * @param <T>
O
Olivier Truong 已提交
1052
     *     Type of the list.
1053
     * @return
O
Olivier Truong 已提交
1054 1055
     *     {@code l} if l is not {@code null}.
     *     An empty <b>immutable list</b> if l is {@code null}.
1056
     */
O
Oleg Nenashev 已提交
1057 1058
    @Nonnull
    public static <T> List<T> fixNull(@CheckForNull List<T> l) {
J
Josh Soref 已提交
1059
        return fixNull(l, Collections.emptyList());
1060 1061
    }

1062 1063
    /**
     *
O
Olivier Truong 已提交
1064
     * @param l set to check.
1065
     * @param <T>
O
Olivier Truong 已提交
1066
     *     Type of the set.
1067
     * @return
O
Olivier Truong 已提交
1068 1069
     *     {@code l} if l is not {@code null}.
     *     An empty <b>immutable set</b> if l is {@code null}.
1070
     */
O
Oleg Nenashev 已提交
1071 1072
    @Nonnull
    public static <T> Set<T> fixNull(@CheckForNull Set<T> l) {
J
Josh Soref 已提交
1073
        return fixNull(l, Collections.emptySet());
1074 1075
    }

1076 1077
    /**
     *
O
Olivier Truong 已提交
1078
     * @param l collection to check.
1079
     * @param <T>
O
Olivier Truong 已提交
1080
     *     Type of the collection.
1081
     * @return
O
Olivier Truong 已提交
1082 1083
     *     {@code l} if l is not {@code null}.
     *     An empty <b>immutable set</b> if l is {@code null}.
1084
     */
O
Oleg Nenashev 已提交
1085 1086
    @Nonnull
    public static <T> Collection<T> fixNull(@CheckForNull Collection<T> l) {
J
Josh Soref 已提交
1087
        return fixNull(l, Collections.emptySet());
1088 1089
    }

1090 1091
    /**
     *
O
Olivier Truong 已提交
1092
     * @param l iterable to check.
1093
     * @param <T>
O
Olivier Truong 已提交
1094
     *     Type of the iterable.
1095
     * @return
O
Olivier Truong 已提交
1096 1097
     *     {@code l} if l is not {@code null}.
     *     An empty <b>immutable set</b> if l is {@code null}.
1098
     */
O
Oleg Nenashev 已提交
1099 1100
    @Nonnull
    public static <T> Iterable<T> fixNull(@CheckForNull Iterable<T> l) {
J
Josh Soref 已提交
1101
        return fixNull(l, Collections.emptySet());
K
kohsuke 已提交
1102 1103
    }

K
kohsuke 已提交
1104 1105 1106
    /**
     * Cuts all the leading path portion and get just the file name.
     */
O
Oleg Nenashev 已提交
1107 1108
    @Nonnull
    public static String getFileName(@Nonnull String filePath) {
K
kohsuke 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117
        int idx = filePath.lastIndexOf('\\');
        if(idx>=0)
            return getFileName(filePath.substring(idx+1));
        idx = filePath.lastIndexOf('/');
        if(idx>=0)
            return getFileName(filePath.substring(idx+1));
        return filePath;
    }

K
kohsuke 已提交
1118 1119 1120
    /**
     * Concatenate multiple strings by inserting a separator.
     */
O
Oleg Nenashev 已提交
1121 1122
    @Nonnull
    public static String join(@Nonnull Collection<?> strings, @Nonnull String separator) {
K
kohsuke 已提交
1123 1124
        StringBuilder buf = new StringBuilder();
        boolean first=true;
1125
        for (Object s : strings) {
K
kohsuke 已提交
1126
            if(first)   first=false;
1127
            else        buf.append(separator);
K
kohsuke 已提交
1128 1129 1130 1131 1132
            buf.append(s);
        }
        return buf.toString();
    }

K
kohsuke 已提交
1133 1134 1135
    /**
     * Combines all the given collections into a single list.
     */
O
Oleg Nenashev 已提交
1136 1137
    @Nonnull
    public static <T> List<T> join(@Nonnull Collection<? extends T>... items) {
K
kohsuke 已提交
1138 1139 1140
        int size = 0;
        for (Collection<? extends T> item : items)
            size += item.size();
1141
        List<T> r = new ArrayList<>(size);
K
kohsuke 已提交
1142 1143 1144 1145 1146
        for (Collection<? extends T> item : items)
            r.addAll(item);
        return r;
    }

1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    /**
     * Creates Ant {@link FileSet} with the base dir and include pattern.
     *
     * <p>
     * The difference with this and using {@link FileSet#setIncludes(String)}
     * is that this method doesn't treat whitespace as a pattern separator,
     * which makes it impossible to use space in the file path.
     *
     * @param includes
     *      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.
K
kohsuke 已提交
1159
     * @param excludes
K
kohsuke 已提交
1160 1161
     *      Exclusion pattern. Follows the same format as the 'includes' parameter.
     *      Can be null.
K
kohsuke 已提交
1162
     * @since 1.172
1163
     */
O
Oleg Nenashev 已提交
1164 1165
    @Nonnull
    public static FileSet createFileSet(@Nonnull File baseDir, @Nonnull String includes, @CheckForNull String excludes) {
1166 1167 1168
        FileSet fs = new FileSet();
        fs.setDir(baseDir);
        fs.setProject(new Project());
K
kohsuke 已提交
1169 1170 1171 1172

        StringTokenizer tokens;

        tokens = new StringTokenizer(includes,",");
1173 1174 1175 1176
        while(tokens.hasMoreTokens()) {
            String token = tokens.nextToken().trim();
            fs.createInclude().setName(token);
        }
K
kohsuke 已提交
1177 1178 1179 1180 1181 1182 1183
        if(excludes!=null) {
            tokens = new StringTokenizer(excludes,",");
            while(tokens.hasMoreTokens()) {
                String token = tokens.nextToken().trim();
                fs.createExclude().setName(token);
            }
        }
1184 1185
        return fs;
    }
K
kohsuke 已提交
1186

O
Oleg Nenashev 已提交
1187 1188
    @Nonnull
    public static FileSet createFileSet(@Nonnull File baseDir, @Nonnull String includes) {
K
kohsuke 已提交
1189 1190 1191
        return createFileSet(baseDir,includes,null);
    }

1192
    /**
1193
     * Creates a symlink to targetPath at baseDir+symlinkPath.
1194 1195
     * <p>
     * If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
1196 1197 1198 1199
     *
     * @param baseDir
     *      Base directory to resolve the 'symlinkPath' parameter.
     * @param targetPath
1200
     *      The file that the symlink should point to. Usually relative to the directory of the symlink but may instead be an absolute path.
1201
     * @param symlinkPath
1202
     *      Where to create a symlink in (relative to {@code baseDir})
1203
     */
1204
    public static void createSymlink(@Nonnull File baseDir, @Nonnull String targetPath,
O
Oleg Nenashev 已提交
1205
            @Nonnull String symlinkPath, @Nonnull TaskListener listener) throws InterruptedException {
1206
        try {
1207
            Path path = fileToPath(new File(baseDir, symlinkPath));
1208
            Path target = Paths.get(targetPath, MemoryReductionUtil.EMPTY_STRING_ARRAY);
1209 1210 1211 1212

            final int maxNumberOfTries = 4;
            final int timeInMillis = 100;
            for (int tryNumber = 1; tryNumber <= maxNumberOfTries; tryNumber++) {
1213
                Files.deleteIfExists(path);
1214
                try {
1215
                    Files.createSymbolicLink(path, target);
1216
                    break;
1217 1218 1219 1220
                } catch (FileAlreadyExistsException fileAlreadyExistsException) {
                    if (tryNumber < maxNumberOfTries) {
                        TimeUnit.MILLISECONDS.sleep(timeInMillis); //trying to defeat likely ongoing race condition
                        continue;
1221
                    }
1222
                    LOGGER.log(Level.WARNING, "symlink FileAlreadyExistsException thrown {0} times => cannot createSymbolicLink", maxNumberOfTries);
1223
                    throw fileAlreadyExistsException;
1224 1225
                }
            }
1226
        } catch (UnsupportedOperationException e) {
1227 1228 1229
            PrintStream log = listener.getLogger();
            log.print("Symbolic links are not supported on this platform");
            Functions.printStackTrace(e, log);
1230
        } catch (IOException e) {
1231
            if (Functions.isWindows() && e instanceof FileSystemException) {
1232
                warnWindowsSymlink();
1233
                return;
1234
            }
1235 1236 1237
            PrintStream log = listener.getLogger();
            log.printf("ln %s %s failed%n",targetPath, new File(baseDir, symlinkPath));
            Functions.printStackTrace(e, log);
1238 1239 1240
        }
    }

1241 1242 1243 1244 1245 1246 1247
    private static final AtomicBoolean warnedSymlinks = new AtomicBoolean();
    private static void warnWindowsSymlink() {
        if (warnedSymlinks.compareAndSet(false, true)) {
            LOGGER.warning("Symbolic links enabled on this platform but disabled for this user; run as administrator or use Local Security Policy > Security Settings > Local Policies > User Rights Assignment > Create symbolic links");
        }
    }

K
Kohsuke Kawaguchi 已提交
1248 1249 1250 1251
    /**
     * @deprecated as of 1.456
     *      Use {@link #resolveSymlink(File)}
     */
1252
    @Deprecated
K
Kohsuke Kawaguchi 已提交
1253 1254 1255 1256
    public static String resolveSymlink(File link, TaskListener listener) throws InterruptedException, IOException {
        return resolveSymlink(link);
    }

K
Kohsuke Kawaguchi 已提交
1257 1258 1259 1260 1261 1262
    /**
     * Resolves a symlink to the {@link File} that points to.
     *
     * @return null
     *      if the specified file is not a symlink.
     */
O
Oleg Nenashev 已提交
1263 1264
    @CheckForNull
    public static File resolveSymlinkToFile(@Nonnull File link) throws InterruptedException, IOException {
K
Kohsuke Kawaguchi 已提交
1265 1266 1267 1268 1269 1270 1271
        String target = resolveSymlink(link);
        if (target==null)   return null;

        File f = new File(target);
        if (f.isAbsolute()) return f;   // absolute symlink
        return new File(link.getParentFile(),target);   // relative symlink
    }
K
Kohsuke Kawaguchi 已提交
1272

K
kohsuke 已提交
1273 1274 1275 1276
    /**
     * Resolves symlink, if the given file is a symlink. Otherwise return null.
     * <p>
     * If the resolution fails, report an error.
K
Kohsuke Kawaguchi 已提交
1277 1278 1279 1280 1281 1282
     *
     * @return
     *      null if the given file is not a symlink.
     *      If the symlink is absolute, the returned string is an absolute path.
     *      If the symlink is relative, the returned string is that relative representation.
     *      The relative path is meant to be resolved from the location of the symlink.
K
kohsuke 已提交
1283
     */
O
Oleg Nenashev 已提交
1284
    @CheckForNull
J
Jesse Glick 已提交
1285
    public static String resolveSymlink(@Nonnull File link) throws IOException {
1286
        try {
1287
            Path path = fileToPath(link);
1288 1289 1290 1291 1292 1293 1294 1295
            return Files.readSymbolicLink(path).toString();
        } catch (UnsupportedOperationException | FileSystemException x) {
            // no symlinks on this platform (windows?),
            // or not a link (// Thrown ("Incorrect function.") on JDK 7u21 in Windows 2012 when called on a non-symlink,
            // rather than NotLinkException, contrary to documentation. Maybe only when not on NTFS?) ?
            return null;
        } catch (IOException x) {
            throw x;
1296
        } catch (Exception x) {
1297
            throw new IOException(x);
1298
        }
1299 1300
    }

1301 1302 1303 1304 1305 1306 1307
    /**
     * Encodes the URL by RFC 2396.
     *
     * I thought there's another spec that refers to UTF-8 as the encoding,
     * but don't remember it right now.
     *
     * @since 1.204
M
mindless 已提交
1308
     * @deprecated since 2008-05-13. This method is broken (see ISSUE#1666). It should probably
1309 1310
     * be removed but I'm not sure if it is considered part of the public API
     * that needs to be maintained for backwards compatibility.
1311
     * Use {@link #encode(String)} instead.
1312
     */
1313
    @Deprecated
1314 1315 1316 1317
    public static String encodeRFC2396(String url) {
        try {
            return new URI(null,url,null).toASCIIString();
        } catch (URISyntaxException e) {
1318
            LOGGER.log(Level.WARNING, "Failed to encode {0}", url);    // could this ever happen?
1319 1320 1321 1322
            return url;
        }
    }

K
kohsuke 已提交
1323 1324
    /**
     * Wraps with the error icon and the CSS class to render error message.
1325
     * @since 1.173
K
kohsuke 已提交
1326
     */
O
Oleg Nenashev 已提交
1327 1328
    @Nonnull
    public static String wrapToErrorSpan(@Nonnull String s) {
1329
        s = "<span class=error style='display:inline-block'>"+s+"</span>";
K
kohsuke 已提交
1330 1331
        return s;
    }
1332

1333 1334 1335 1336 1337 1338 1339 1340
    /**
     * Returns the parsed string if parsed successful; otherwise returns the default number.
     * If the string is null, empty or a ParseException is thrown then the defaultNumber
     * is returned.
     * @param numberStr string to parse
     * @param defaultNumber number to return if the string can not be parsed
     * @return returns the parsed string; otherwise the default number
     */
O
Oleg Nenashev 已提交
1341 1342
    @CheckForNull
    public static Number tryParseNumber(@CheckForNull String numberStr, @CheckForNull Number defaultNumber) {
1343 1344 1345 1346 1347 1348 1349 1350 1351
        if ((numberStr == null) || (numberStr.length() == 0)) {
            return defaultNumber;
        }
        try {
            return NumberFormat.getNumberInstance().parse(numberStr);
        } catch (ParseException e) {
            return defaultNumber;
        }
    }
K
kohsuke 已提交
1352

1353
    /**
1354 1355
     * Checks if the method defined on the base type with the given arguments
     * is overridden in the given derived type.
1356
     */
O
Oleg Nenashev 已提交
1357
    public static boolean isOverridden(@Nonnull Class base, @Nonnull Class derived, @Nonnull String methodName, @Nonnull Class... types) {
1358 1359 1360 1361 1362
        return !getMethod(base, methodName, types).equals(getMethod(derived, methodName, types));
    }

    private static Method getMethod(@Nonnull Class clazz, @Nonnull String methodName, @Nonnull Class... types) {
        Method res = null;
1363
        try {
1364 1365 1366 1367 1368 1369
            res = clazz.getDeclaredMethod(methodName, types);
            // private, static or final methods can not be overridden
            if (res != null && (Modifier.isPrivate(res.getModifiers()) || Modifier.isFinal(res.getModifiers()) 
                    || Modifier.isStatic(res.getModifiers()))) {
                res = null;
            }
1370
        } catch (NoSuchMethodException e) {
1371 1372 1373 1374 1375 1376
            // Method not found in clazz, let's search in superclasses
            Class superclass = clazz.getSuperclass();
            if (superclass != null) {
                res = getMethod(superclass, methodName, types);
            }
        } catch (SecurityException e) {
1377 1378
            throw new AssertionError(e);
        }
1379 1380 1381 1382 1383
        if (res == null) {
            throw new IllegalArgumentException(
                    String.format("Method %s not found in %s (or it is private, final or static)", methodName, clazz.getName()));
        }
        return res;
1384 1385
    }

1386 1387 1388 1389 1390 1391
    /**
     * Returns a file name by changing its extension.
     *
     * @param ext
     *      For example, ".zip"
     */
O
Oleg Nenashev 已提交
1392 1393
    @Nonnull
    public static File changeExtension(@Nonnull File dst, @Nonnull String ext) {
1394 1395 1396 1397 1398 1399
        String p = dst.getPath();
        int pos = p.lastIndexOf('.');
        if (pos<0)  return new File(p+ext);
        else        return new File(p.substring(0,pos)+ext);
    }

K
kohsuke 已提交
1400 1401
    /**
     * Null-safe String intern method.
1402
     * @return A canonical representation for the string object. Null for null input strings
K
kohsuke 已提交
1403
     */
1404
    @Nullable
O
Oleg Nenashev 已提交
1405
    public static String intern(@CheckForNull String s) {
K
kohsuke 已提交
1406 1407 1408
        return s==null ? s : s.intern();
    }

K
Kohsuke Kawaguchi 已提交
1409 1410 1411 1412 1413 1414
    /**
     * Return true if the systemId denotes an absolute URI .
     *
     * The same algorithm can be seen in {@link URI}, but
     * implementing this by ourselves allow it to be more lenient about
     * escaping of URI.
1415 1416
     *
     * @deprecated Use {@code isAbsoluteOrSchemeRelativeUri} instead if your goal is to prevent open redirects
K
Kohsuke Kawaguchi 已提交
1417
     */
1418 1419 1420
    @Deprecated
    @RestrictedSince("1.651.2 / 2.TODO")
    @Restricted(NoExternalUse.class)
O
Oleg Nenashev 已提交
1421
    public static boolean isAbsoluteUri(@Nonnull String uri) {
K
Kohsuke Kawaguchi 已提交
1422 1423 1424 1425 1426 1427 1428
        int idx = uri.indexOf(':');
        if (idx<0)  return false;   // no ':'. can't be absolute

        // #, ?, and / must not be before ':'
        return idx<_indexOf(uri, '#') && idx<_indexOf(uri,'?') && idx<_indexOf(uri,'/');
    }

1429
    /**
1430
     * Return true iff the parameter does not denote an absolute URI and not a scheme-relative URI.
1431
     * @since 2.3 / 1.651.2
1432
     */
1433 1434
    public static boolean isSafeToRedirectTo(@Nonnull String uri) {
        return !isAbsoluteUri(uri) && !uri.startsWith("//");
1435 1436
    }

K
Kohsuke Kawaguchi 已提交
1437 1438 1439 1440
    /**
     * Works like {@link String#indexOf(int)} but 'not found' is returned as s.length(), not -1.
     * This enables more straight-forward comparison.
     */
O
Oleg Nenashev 已提交
1441
    private static int _indexOf(@Nonnull String s, char ch) {
K
Kohsuke Kawaguchi 已提交
1442 1443 1444 1445 1446
        int idx = s.indexOf(ch);
        if (idx<0)  return s.length();
        return idx;
    }

1447 1448 1449 1450
    /**
     * Loads a key/value pair string as {@link Properties}
     * @since 1.392
     */
O
Oleg Nenashev 已提交
1451 1452
    @Nonnull
    public static Properties loadProperties(@Nonnull String properties) throws IOException {
1453
        Properties p = new Properties();
1454
        p.load(new StringReader(properties));
1455 1456
        return p;
    }
1457 1458 1459 1460 1461 1462 1463 1464
    
    /**
     * Closes the item and logs error to the log in the case of error.
     * Logging will be performed on the {@code WARNING} level.
     * @param toClose Item to close. Nothing will happen if it is {@code null}
     * @param logger Logger, which receives the error
     * @param closeableName Name of the closeable item
     * @param closeableOwner String representation of the closeable holder
D
Daniel Beck 已提交
1465
     * @since 2.19, but TODO update once un-restricted
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
     */
    @Restricted(NoExternalUse.class)
    public static void closeAndLogFailures(@CheckForNull Closeable toClose, @Nonnull Logger logger, 
            @Nonnull String closeableName, @Nonnull String closeableOwner) {
        if (toClose == null) {
            return;
        }
        try {
            toClose.close();
        } catch(IOException ex) {
1476 1477 1478 1479
            LogRecord record = new LogRecord(Level.WARNING, "Failed to close {0} of {1}");
            record.setParameters(new Object[] { closeableName, closeableOwner });
            record.setThrown(ex);
            logger.log(record);
1480 1481
        }
    }
1482

1483 1484 1485 1486
    @Restricted(NoExternalUse.class)
    public static int permissionsToMode(Set<PosixFilePermission> permissions) {
        PosixFilePermission[] allPermissions = PosixFilePermission.values();
        int result = 0;
J
Josh Soref 已提交
1487
        for (PosixFilePermission allPermission : allPermissions) {
1488
            result <<= 1;
J
Josh Soref 已提交
1489
            result |= permissions.contains(allPermission) ? 1 : 0;
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
        }
        return result;
    }

    @Restricted(NoExternalUse.class)
    public static Set<PosixFilePermission> modeToPermissions(int mode) throws IOException {
         // Anything larger is a file type, not a permission.
        int PERMISSIONS_MASK = 07777;
        // setgid/setuid/sticky are not supported.
        int MAX_SUPPORTED_MODE = 0777;
        mode = mode & PERMISSIONS_MASK;
        if ((mode & MAX_SUPPORTED_MODE) != mode) {
            throw new IOException("Invalid mode: " + mode);
        }
        PosixFilePermission[] allPermissions = PosixFilePermission.values();
        Set<PosixFilePermission> result = EnumSet.noneOf(PosixFilePermission.class);
        for (int i = 0; i < allPermissions.length; i++) {
            if ((mode & 1) == 1) {
                result.add(allPermissions[allPermissions.length - i - 1]);
            }
            mode >>= 1;
        }
        return result;
    }

    /**
     * Converts a {@link File} into a {@link Path} and checks runtime exceptions.
     * @throws IOException if {@code f.toPath()} throws {@link InvalidPathException}.
     */
    @Restricted(NoExternalUse.class)
    public static @Nonnull Path fileToPath(@Nonnull File file) throws IOException {
        try {
            return file.toPath();
        } catch (InvalidPathException e) {
            throw new IOException(e);
        }
    }
1527 1528 1529 1530 1531 1532 1533
    
    /**
     * Compute the number of calendar days elapsed since the given date.
     * As it's only the calendar days difference that matter, "11.00pm" to "2.00am the day after" returns 1,
     * even if there are only 3 hours between. As well as "10am" to "2pm" both on the same day, returns 0.
     */
    @Restricted(NoExternalUse.class)
W
Wadeck Follonier 已提交
1534
    public static long daysBetween(@Nonnull Date a, @Nonnull Date b){
1535 1536
        LocalDate aLocal = a.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate bLocal = b.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
W
Wadeck Follonier 已提交
1537
        return ChronoUnit.DAYS.between(aLocal, bLocal);
1538 1539 1540
    }
    
    /**
W
Wadeck Follonier 已提交
1541 1542
     * @return positive number of days between the given date and now
     * @see #daysBetween(Date, Date)
1543 1544
     */
    @Restricted(NoExternalUse.class)
W
Wadeck Follonier 已提交
1545 1546
    public static long daysElapsedSince(@Nonnull Date date){
        return Math.max(0, daysBetween(date, new Date()));
1547 1548
    }
    
W
Wadeck Follonier 已提交
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
    /**
     * Find the specific ancestor, or throw an exception.
     * Useful for an ancestor we know is inside the URL to ease readability
     */
    @Restricted(NoExternalUse.class)
    public static @Nonnull <T> T getNearestAncestorOfTypeOrThrow(@Nonnull StaplerRequest request, @Nonnull Class<T> clazz) {
        T t = request.findAncestorObject(clazz);
        if (t == null) {
            throw new IllegalArgumentException("No ancestor of type " + clazz.getName() + " in the request");
        }
        return t;
    }

1562
    public static final FastDateFormat XS_DATETIME_FORMATTER = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'",new SimpleTimeZone(0,"GMT"));
K
kohsuke 已提交
1563

1564
    // Note: RFC822 dates must not be localized!
1565 1566
    public static final FastDateFormat RFC822_DATETIME_FORMATTER
            = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
K
kohsuke 已提交
1567 1568

    private static final Logger LOGGER = Logger.getLogger(Util.class.getName());
1569 1570 1571 1572

    /**
     * On Unix environment that cannot run "ln", set this to true.
     */
1573
    public static boolean NO_SYMLINK = SystemProperties.getBoolean(Util.class.getName()+".noSymLink");
1574

1575
    public static boolean SYMLINK_ESCAPEHATCH = SystemProperties.getBoolean(Util.class.getName()+".symlinkEscapeHatch");
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591

    /**
     * The number of times we will attempt to delete files/directory trees
     * before giving up and throwing an exception.<br/>
     * Specifying a value less than 1 is invalid and will be treated as if
     * a value of 1 (i.e. one attempt, no retries) was specified.
     * <p>
     * e.g. if some of the child directories are big, it might take long enough
     * to delete that it allows others to create new files in the directory we
     * are trying to empty, causing problems like JENKINS-10113.
     * Or, if we're on Windows, then deletes can fail for transient reasons
     * regardless of external activity; see JENKINS-15331.
     * Whatever the reason, this allows us to do multiple attempts before we
     * give up, thus improving build reliability.
     */
    @Restricted(value = NoExternalUse.class)
J
Josh Soref 已提交
1592
    static int DELETION_MAX = Math.max(1, SystemProperties.getInteger(Util.class.getName() + ".maxFileDeletionRetries", 3));
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603

    /**
     * The time (in milliseconds) that we will wait between attempts to
     * delete files when retrying.<br>
     * This has no effect unless {@link #DELETION_MAX} is non-zero.
     * <p>
     * If zero, we will not delay between attempts.<br>
     * If negative, we will wait an (linearly) increasing multiple of this value
     * between attempts.
     */
    @Restricted(value = NoExternalUse.class)
J
Josh Soref 已提交
1604
    static int WAIT_BETWEEN_DELETION_RETRIES = SystemProperties.getInteger(Util.class.getName() + ".deletionRetryWait", 100);
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619

    /**
     * If this flag is set to true then we will request a garbage collection
     * after a deletion failure before we next retry the delete.<br>
     * It defaults to <code>false</code> and is ignored unless
     * {@link #DELETION_MAX} is greater than 1.
     * <p>
     * Setting this flag to true <i>may</i> resolve some problems on Windows,
     * and also for directory trees residing on an NFS share, <b>but</b> it can
     * have a negative impact on performance and may have no effect at all (GC
     * behavior is JVM-specific).
     * <p>
     * Warning: This should only ever be used if you find that your builds are
     * failing because Jenkins is unable to delete files, that this failure is
     * because Jenkins itself has those files locked "open", and even then it
1620
     * should only be used on agents with relatively few executors (because the
1621 1622 1623 1624 1625 1626 1627
     * garbage collection can impact the performance of all job executors on
     * that slave).<br/>
     * i.e. Setting this flag is a act of last resort - it is <em>not</em>
     * recommended, and should not be used on the main Jenkins server
     * unless you can tolerate the performance impact.
     */
    @Restricted(value = NoExternalUse.class)
1628
    static boolean GC_AFTER_FAILED_DELETE = SystemProperties.getBoolean(Util.class.getName() + ".performGCOnFailedDelete");
1629

1630 1631
    private static PathRemover newPathRemover(@Nonnull PathRemover.PathChecker pathChecker) {
        return PathRemover.newFilteredRobustRemover(pathChecker, DELETION_MAX - 1, GC_AFTER_FAILED_DELETE, WAIT_BETWEEN_DELETION_RETRIES);
1632 1633
    }

1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
    /**
     * If this flag is true, native implementations of {@link FilePath#chmod}
     * and {@link hudson.util.IOUtils#mode} are used instead of NIO.
     * <p>
     * This should only be enabled if the setgid/setuid/sticky bits are
     * intentionally set on the Jenkins installation and they are being
     * overwritten by Jenkins erroneously.
     */
    @Restricted(value = NoExternalUse.class)
    public static boolean NATIVE_CHMOD_MODE = SystemProperties.getBoolean(Util.class.getName() + ".useNativeChmodAndMode");
K
kohsuke 已提交
1644
}