aboutsummaryrefslogtreecommitdiffstats
path: root/org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/time/TimeUtil.java
blob: f93ac57f13ea7eb6d3ea1e731aaa2f83d60896bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
 * Copyright (C) 2019, Matthias Sohn <matthias.sohn@sap.com> and others
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Distribution License v. 1.0 which is available at
 * https://www.eclipse.org/org/documents/edl-v10.php.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */
package org.eclipse.jgit.junit.time;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.time.Instant;

import org.eclipse.jgit.util.FS;

/**
 * Utility methods for handling timestamps
 *
 * @since 5.1.9
 */
public class TimeUtil {
	/**
	 * Set the lastModified time of a given file by adding a given offset to the
	 * current lastModified time
	 *
	 * @param path
	 *            path of a file to set last modified
	 * @param offsetMillis
	 *            offset in milliseconds, if negative the new lastModified time
	 *            is offset before the original lastModified time, otherwise
	 *            after the original time
	 * @return the new lastModified time
	 */
	public static Instant setLastModifiedWithOffset(Path path,
			long offsetMillis) {
		Instant mTime = FS.DETECTED.lastModifiedInstant(path)
				.plusMillis(offsetMillis);
		try {
			Files.setLastModifiedTime(path, FileTime.from(mTime));
			return mTime;
		} catch (IOException e) {
			throw new UncheckedIOException(e);
		}
	}

	/**
	 * Set the lastModified time of file a to the one from file b
	 *
	 * @param a
	 *            file to set lastModified time
	 * @param b
	 *            file to read lastModified time from
	 */
	public static void setLastModifiedOf(Path a, Path b) {
		Instant mTime = FS.DETECTED.lastModifiedInstant(b);
		try {
			Files.setLastModifiedTime(a, FileTime.from(mTime));
		} catch (IOException e) {
			throw new UncheckedIOException(e);
		}
	}

}