View Javadoc
1   /*
2    * Copyright (C) 2009, Google Inc. 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  
11  package org.eclipse.jgit.internal.storage.file;
12  
13  import java.io.File;
14  import java.io.IOException;
15  
16  import org.eclipse.jgit.lib.Constants;
17  import org.eclipse.jgit.util.FS;
18  import org.eclipse.jgit.util.FileUtils;
19  
20  /**
21   * Keeps track of a {@link org.eclipse.jgit.internal.storage.file.PackFile}'s
22   * associated <code>.keep</code> file.
23   */
24  public class PackLock {
25  	private final File keepFile;
26  
27  	/**
28  	 * Create a new lock for a pack file.
29  	 *
30  	 * @param packFile
31  	 *            location of the <code>pack-*.pack</code> file.
32  	 * @param fs
33  	 *            the filesystem abstraction used by the repository.
34  	 */
35  	public PackLock(File packFile, FS fs) {
36  		final File p = packFile.getParentFile();
37  		final String n = packFile.getName();
38  		keepFile = new File(p, n.substring(0, n.length() - 5) + ".keep"); //$NON-NLS-1$
39  	}
40  
41  	/**
42  	 * Create the <code>pack-*.keep</code> file, with the given message.
43  	 *
44  	 * @param msg
45  	 *            message to store in the file.
46  	 * @return true if the keep file was successfully written; false otherwise.
47  	 * @throws java.io.IOException
48  	 *             the keep file could not be written.
49  	 */
50  	public boolean lock(String msg) throws IOException {
51  		if (msg == null)
52  			return false;
53  		if (!msg.endsWith("\n")) //$NON-NLS-1$
54  			msg += "\n"; //$NON-NLS-1$
55  		final LockFileernal/storage/file/LockFile.html#LockFile">LockFile lf = new LockFile(keepFile);
56  		if (!lf.lock())
57  			return false;
58  		lf.write(Constants.encode(msg));
59  		return lf.commit();
60  	}
61  
62  	/**
63  	 * Remove the <code>.keep</code> file that holds this pack in place.
64  	 *
65  	 * @throws java.io.IOException
66  	 *             if deletion of .keep file failed
67  	 */
68  	public void unlock() throws IOException {
69  		FileUtils.delete(keepFile);
70  	}
71  }