001package co.codewizards.cloudstore.client; 002 003import static co.codewizards.cloudstore.core.util.Util.*; 004 005import java.io.File; 006 007import org.kohsuke.args4j.Argument; 008 009import co.codewizards.cloudstore.core.repo.local.LocalRepoHelper; 010import co.codewizards.cloudstore.core.repo.local.LocalRepoRegistry; 011import co.codewizards.cloudstore.core.util.IOUtil; 012 013public abstract class SubCommandWithExistingLocalRepo extends SubCommand { 014 015 @Argument(metaVar="<local>", required=true, index=0, usage="A path inside a repository in the local file system or a " 016 + "repository-ID or a repository-alias (optionally with a path). If this matches both a locally " 017 + "existing directory and a repository-ID/-alias, it is assumed to be a repository-ID/-alias. " 018 + "Note, that it may be a sub-directory inside the repository specified in the form " 019 + "<repositoryId>/path (this must be a '/' even on Windows).") 020 protected String local; 021 022 protected String localPathPrefix; 023 024 /** 025 * {@link File} referencing a directory inside the repository (or its root). 026 */ 027 protected File localFile; 028 029 /** 030 * The root directory of the repository. 031 * <p> 032 * This may be the same as {@link #localFile} or it may be 033 * a direct or indirect parent-directory of {@code #localFile}. 034 */ 035 protected File localRoot; 036 037 @Override 038 public void prepare() throws Exception { 039 super.prepare(); 040 assertNotNull("local", local); 041 042 String repositoryName; 043 int slashIndex = local.indexOf('/'); 044 if (slashIndex < 0) { 045 repositoryName = local; 046 localPathPrefix = ""; 047 } 048 else { 049 repositoryName = local.substring(0, slashIndex); 050 localPathPrefix = local.substring(slashIndex); 051 052 if (!localPathPrefix.startsWith("/")) 053 throw new IllegalStateException("localPathPrefix does not start with '/': " + localPathPrefix); 054 } 055 056 if ("/".equals(localPathPrefix)) 057 localPathPrefix = ""; 058 059 localRoot = LocalRepoRegistry.getInstance().getLocalRootForRepositoryName(repositoryName); 060 if (localRoot != null) 061 localFile = localPathPrefix.isEmpty() ? localRoot : new File(localRoot, localPathPrefix); 062 else { 063 localFile = new File(local).getAbsoluteFile(); 064 localRoot = LocalRepoHelper.getLocalRootContainingFile(localFile); 065 if (localRoot == null) 066 localRoot = localFile; 067 068 if (localRoot.equals(localFile)) 069 localPathPrefix = ""; 070 else 071 localPathPrefix = IOUtil.getRelativePath(localRoot, localFile); 072 } 073 assertLocalRootNotNull(); 074 } 075 076 protected void assertLocalRootNotNull() { 077 assertNotNull("localRoot", localRoot); 078 } 079 080}