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