PackLockImpl.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.transport.PackLock;
  15. import org.eclipse.jgit.util.FS;
  16. import org.eclipse.jgit.util.FileUtils;

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

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

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

  56.     @Override
  57.     public void unlock() throws IOException {
  58.         FileUtils.delete(keepFile);
  59.     }
  60. }