PackLock.java

  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. package org.eclipse.jgit.internal.storage.file;

  11. import java.io.File;
  12. import java.io.IOException;

  13. import org.eclipse.jgit.lib.Constants;
  14. import org.eclipse.jgit.util.FS;
  15. import org.eclipse.jgit.util.FileUtils;

  16. /**
  17.  * Keeps track of a {@link org.eclipse.jgit.internal.storage.file.Pack}'s
  18.  * associated <code>.keep</code> file.
  19.  */
  20. public class PackLock {
  21.     private final File keepFile;

  22.     /**
  23.      * Create a new lock for a pack file.
  24.      *
  25.      * @param packFile
  26.      *            location of the <code>pack-*.pack</code> file.
  27.      * @param fs
  28.      *            the filesystem abstraction used by the repository.
  29.      */
  30.     public PackLock(File packFile, FS fs) {
  31.         final File p = packFile.getParentFile();
  32.         final String n = packFile.getName();
  33.         keepFile = new File(p, n.substring(0, n.length() - 5) + ".keep"); //$NON-NLS-1$
  34.     }

  35.     /**
  36.      * Create the <code>pack-*.keep</code> file, with the given message.
  37.      *
  38.      * @param msg
  39.      *            message to store in the file.
  40.      * @return true if the keep file was successfully written; false otherwise.
  41.      * @throws java.io.IOException
  42.      *             the keep file could not be written.
  43.      */
  44.     public boolean lock(String msg) throws IOException {
  45.         if (msg == null)
  46.             return false;
  47.         if (!msg.endsWith("\n")) //$NON-NLS-1$
  48.             msg += "\n"; //$NON-NLS-1$
  49.         final LockFile lf = new LockFile(keepFile);
  50.         if (!lf.lock())
  51.             return false;
  52.         lf.write(Constants.encode(msg));
  53.         return lf.commit();
  54.     }

  55.     /**
  56.      * Remove the <code>.keep</code> file that holds this pack in place.
  57.      *
  58.      * @throws java.io.IOException
  59.      *             if deletion of .keep file failed
  60.      */
  61.     public void unlock() throws IOException {
  62.         FileUtils.delete(keepFile);
  63.     }
  64. }