1 /*
2 * Copyright (C) 2019, Matthias Sohn <matthias.sohn@sap.com> and others
3 *
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Distribution License v. 1.0 which is available at
6 * https://www.eclipse.org/org/documents/edl-v10.php.
7 *
8 * SPDX-License-Identifier: BSD-3-Clause
9 */
10 package org.eclipse.jgit.junit.time;
11
12 import java.io.IOException;
13 import java.io.UncheckedIOException;
14 import java.nio.file.Files;
15 import java.nio.file.Path;
16 import java.nio.file.attribute.FileTime;
17 import java.time.Instant;
18
19 import org.eclipse.jgit.util.FS;
20
21 /**
22 * Utility methods for handling timestamps
23 */
24 public class TimeUtil {
25 /**
26 * Set the lastModified time of a given file by adding a given offset to the
27 * current lastModified time
28 *
29 * @param path
30 * path of a file to set last modified
31 * @param offsetMillis
32 * offset in milliseconds, if negative the new lastModified time
33 * is offset before the original lastModified time, otherwise
34 * after the original time
35 * @return the new lastModified time
36 */
37 public static Instant setLastModifiedWithOffset(Path path,
38 long offsetMillis) {
39 Instant mTime = FS.DETECTED.lastModifiedInstant(path)
40 .plusMillis(offsetMillis);
41 try {
42 Files.setLastModifiedTime(path, FileTime.from(mTime));
43 return mTime;
44 } catch (IOException e) {
45 throw new UncheckedIOException(e);
46 }
47 }
48
49 /**
50 * Set the lastModified time of file a to the one from file b
51 *
52 * @param a
53 * file to set lastModified time
54 * @param b
55 * file to read lastModified time from
56 */
57 public static void setLastModifiedOf(Path a, Path b) {
58 Instant mTime = FS.DETECTED.lastModifiedInstant(b);
59 try {
60 Files.setLastModifiedTime(a, FileTime.from(mTime));
61 } catch (IOException e) {
62 throw new UncheckedIOException(e);
63 }
64 }
65
66 }