下面列出了org.jetbrains.annotations.SystemIndependent#com.intellij.util.PathUtil 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private MultiValuesMap<String, Artifact> computeParentPathToArtifactMap() {
final MultiValuesMap<String, Artifact> result = new MultiValuesMap<String, Artifact>();
for (final Artifact artifact : myArtifactManager.getArtifacts()) {
ArtifactUtil.processFileOrDirectoryCopyElements(artifact, new PackagingElementProcessor<FileOrDirectoryCopyPackagingElement<?>>() {
@Override
public boolean process(@Nonnull FileOrDirectoryCopyPackagingElement<?> element, @Nonnull PackagingElementPath pathToElement) {
String path = element.getFilePath();
while (path.length() > 0) {
result.put(path, artifact);
path = PathUtil.getParentPath(path);
}
return true;
}
}, myArtifactManager.getResolvingContext(), false);
}
return result;
}
private static String findTestDataPath() {
if (new File(PathManager.getHomePath() + "/contrib").isDirectory()) {
// started from IntelliJ IDEA Ultimate project
return FileUtil.toSystemIndependentName(PathManager.getHomePath() + "/contrib/flutter-intellij/testData");
}
final File f = new File("testData");
if (f.isDirectory()) {
// started from flutter plugin project
return FileUtil.toSystemIndependentName(f.getAbsolutePath());
}
final String parentPath = PathUtil.getParentPath(PathManager.getHomePath());
if (new File(parentPath + "/intellij-plugins").isDirectory()) {
// started from IntelliJ IDEA Community Edition + flutter plugin project
return FileUtil.toSystemIndependentName(parentPath + "/intellij-plugins/flutter-intellij/testData");
}
if (new File(parentPath + "/contrib").isDirectory()) {
// started from IntelliJ IDEA Community + flutter plugin project
return FileUtil.toSystemIndependentName(parentPath + "/contrib/flutter-intellij/testData");
}
return "";
}
public File createLocalFile(@Nonnull String url) throws IOException {
int ast = url.indexOf('?');
if (ast != -1) {
url = url.substring(0, ast);
}
int last = url.lastIndexOf('/');
String baseName;
if (last == url.length() - 1) {
baseName = url.substring(url.lastIndexOf('/', last-1) + 1, last);
}
else {
baseName = url.substring(last + 1);
}
int index = baseName.lastIndexOf('.');
String prefix = index == -1 ? baseName : baseName.substring(0, index);
String suffix = index == -1 ? "" : baseName.substring(index+1);
prefix = PathUtil.suggestFileName(prefix);
suffix = PathUtil.suggestFileName(suffix);
File file = FileUtil.findSequentNonexistentFile(myStorageIODirectory, prefix, suffix);
FileUtil.createIfDoesntExist(file);
return file;
}
private static String findTestDataPath() {
if (new File(PathManager.getHomePath() + "/contrib").isDirectory()) {
// started from IntelliJ IDEA Ultimate project
return FileUtil.toSystemIndependentName(PathManager.getHomePath() + "/contrib/flutter-intellij/testData");
}
final File f = new File("testData");
if (f.isDirectory()) {
// started from flutter plugin project
return FileUtil.toSystemIndependentName(f.getAbsolutePath());
}
final String parentPath = PathUtil.getParentPath(PathManager.getHomePath());
if (new File(parentPath + "/intellij-plugins").isDirectory()) {
// started from IntelliJ IDEA Community Edition + flutter plugin project
return FileUtil.toSystemIndependentName(parentPath + "/intellij-plugins/flutter-intellij/testData");
}
if (new File(parentPath + "/contrib").isDirectory()) {
// started from IntelliJ IDEA Community + flutter plugin project
return FileUtil.toSystemIndependentName(parentPath + "/contrib/flutter-intellij/testData");
}
return "";
}
@Nullable
@Override
protected DirectoryEntry parseItem(ProjectViewParser parser, ParseContext parseContext) {
String text = parseContext.current().text;
boolean excluded = text.startsWith("-");
text = excluded ? text.substring(1) : text;
// removes '.' path sections, traverses ".." without handling symlinks
text = PathUtil.getCanonicalPath(text);
String error = WorkspacePath.validate(text);
if (error != null) {
parseContext.addError(error);
return null;
}
WorkspacePath directory = new WorkspacePath(text);
return excluded ? DirectoryEntry.exclude(directory) : DirectoryEntry.include(directory);
}
/**
* The cache key used to disambiguate output artifacts. This is also the file name in the local
* cache.
*/
@VisibleForTesting
static String getCacheKey(RemoteOutputArtifact output) {
String key = output.getKey();
String fileName = PathUtil.getFileName(key);
List<String> components = Splitter.on('.').limit(2).splitToList(fileName);
StringBuilder builder =
new StringBuilder(components.get(0))
.append('_')
.append(Integer.toHexString(key.hashCode()));
if (components.size() > 1) {
// file extension(s)
builder.append('.').append(components.get(1));
}
return builder.toString();
}
@Nonnull
@Override
public CellAppearanceEx forLibrary(Project project, @Nonnull final Library library, final boolean hasInvalidRoots) {
final StructureConfigurableContext context = ProjectStructureConfigurable.getInstance(project).getContext();
final Image icon = LibraryPresentationManager.getInstance().getCustomIcon(library, context);
final String name = library.getName();
if (name != null) {
return normalOrRedWaved(name, (icon != null ? icon : AllIcons.Nodes.PpLib), hasInvalidRoots);
}
final String[] files = library.getUrls(BinariesOrderRootType.getInstance());
if (files.length == 0) {
return SimpleTextCellAppearance.invalid(ProjectBundle.message("library.empty.library.item"), AllIcons.Nodes.PpLib);
}
else if (files.length == 1) {
return forVirtualFilePointer(new LightFilePointer(files[0]));
}
final String url = StringUtil.trimEnd(files[0], URLUtil.ARCHIVE_SEPARATOR);
return SimpleTextCellAppearance.regular(PathUtil.getFileName(url), AllIcons.Nodes.PpLib);
}
public FileCopyPresentation(String filePath, String outputFileName) {
myOutputFileName = outputFileName;
String parentPath;
myFile = LocalFileSystem.getInstance().findFileByPath(filePath);
if (myFile != null) {
final VirtualFile parent = myFile.getParent();
parentPath = parent != null ? FileUtil.toSystemDependentName(parent.getPath()) : "";
}
else {
parentPath = FileUtil.toSystemDependentName(PathUtil.getParentPath(filePath));
}
String sourceFileName = PathUtil.getFileName(filePath);
if (!sourceFileName.equals(myOutputFileName)) {
mySourcePath = parentPath + "/" + sourceFileName;
}
else {
mySourcePath = parentPath;
}
}
/**
* Return a map from a base label string -> variants of the label string that share the common
* base.
*/
public static Multimap<String, String> getAllValidLabelStringsPartitioned(
Label label, boolean includePackageLocalLabels) {
Multimap<String, String> stringToVariant = ArrayListMultimap.create();
String fullLabelString = label.toString();
List<String> fullVariants = new ArrayList<>();
fullVariants.add(fullLabelString);
String packagePath = label.blazePackage().relativePath();
String ruleName = label.targetName().toString();
if (!packagePath.isEmpty()) {
if (PathUtil.getFileName(packagePath).equals(ruleName)) {
String implicitRuleName = "//" + packagePath;
fullVariants.add(implicitRuleName);
fullLabelString = implicitRuleName;
}
}
stringToVariant.putAll(fullLabelString, fullVariants);
if (!includePackageLocalLabels) {
return stringToVariant;
}
List<String> localVariants = new ArrayList<>();
localVariants.add(":" + ruleName);
localVariants.add(ruleName);
stringToVariant.putAll(ruleName, localVariants);
return stringToVariant;
}
public static void updateFileExtension(@Nonnull Project project, @Nullable VirtualFile file) throws IOException {
ApplicationManager.getApplication().assertWriteAccessAllowed();
if (CommandProcessor.getInstance().getCurrentCommand() == null) {
throw new AssertionError("command required");
}
if (file == null) return;
Language language = LanguageUtil.getLanguageForPsi(project, file);
FileType expected = getFileTypeFromName(file);
FileType actual = language == null ? null : language.getAssociatedFileType();
if (expected == actual || actual == null) return;
String ext = actual.getDefaultExtension();
if (StringUtil.isEmpty(ext)) return;
String newName = PathUtil.makeFileName(file.getNameWithoutExtension(), ext);
VirtualFile parent = file.getParent();
newName = parent != null && parent.findChild(newName) != null ? PathUtil.makeFileName(file.getName(), ext) : newName;
file.rename(ScratchUtil.class, newName);
}
private Set<VirtualFile> getNotExcludedRoots() {
Set<VirtualFile> roots = new LinkedHashSet<VirtualFile>();
String[] excludedRootUrls = getLibraryEditor().getExcludedRootUrls();
Set<VirtualFile> excludedRoots = new HashSet<VirtualFile>();
for (String url : excludedRootUrls) {
ContainerUtil.addIfNotNull(excludedRoots, VirtualFileManager.getInstance().findFileByUrl(url));
}
for (OrderRootType type : OrderRootType.getAllTypes()) {
VirtualFile[] files = getLibraryEditor().getFiles(type);
for (VirtualFile file : files) {
if (!VfsUtilCore.isUnder(file, excludedRoots)) {
roots.add(PathUtil.getLocalFile(file));
}
}
}
return roots;
}
@Nullable
@Override
public PsiElement resolveInner() {
final String referencedName = cmd.getReferencedCommandName();
if (referencedName == null) {
return null;
}
String fileName = PathUtil.getFileName(referencedName);
GlobalSearchScope scope = BashSearchScopes.moduleScope(cmd.getContainingFile());
PsiFileSystemItem[] files = FilenameIndex.getFilesByName(cmd.getProject(), fileName, scope, false);
if (files.length == 0) {
return null;
}
PsiFile currentFile = cmd.getContainingFile();
return BashPsiFileUtils.findRelativeFile(currentFile, referencedName);
}
@NotNull
private static String loadProjectStructureFromScript(
@NotNull String scriptPath,
@NotNull Consumer<String> statusConsumer,
@Nullable ProcessAdapter processAdapter
) throws IOException, ExecutionException {
final GeneralCommandLine commandLine = PantsUtil.defaultCommandLine(scriptPath);
commandLine.setExePath(scriptPath);
statusConsumer.consume("Executing " + PathUtil.getFileName(scriptPath));
final ProcessOutput processOutput = PantsUtil.getCmdOutput(commandLine, processAdapter);
if (processOutput.checkSuccess(LOG)) {
return processOutput.getStdout();
}
else {
throw new PantsExecutionException("Failed to update the project!", scriptPath, processOutput);
}
}
@Override
public boolean contains(@Nonnull VirtualFile file) {
final PsiDirectory value = getValue();
if (value == null) {
return false;
}
VirtualFile directory = value.getVirtualFile();
if (directory.getFileSystem() instanceof LocalFileSystem) {
file = PathUtil.getLocalFile(file);
}
if (!VfsUtilCore.isAncestor(directory, file, false)) {
return false;
}
return !FileTypeRegistry.getInstance().isFileIgnored(file);
}
@NotNull
private static String calculateWorkingPath(CompilationContext context) {
HaxeModuleSettingsBase settings = context.getModuleSettings();
// TODO: Add a setting for the working directory to the project/module settings dialog. Then use that here.
String workingPath = null;
if (settings.isUseOpenFLToBuild()) {
// Use the module directory...
workingPath = context.getModuleDirPath();
} else if (settings.isUseNmmlToBuild()) {
String nmmlPath = settings.getNmmlPath();
workingPath = PathUtil.getParentPath(nmmlPath);
} else if (settings.isUseHxmlToBuild()) {
String hxmlPath = settings.getHxmlPath();
workingPath = PathUtil.getParentPath(hxmlPath);
} else if (settings.isUseUserPropertiesToBuild()) {
workingPath = findCwdInCommandLineArguments(settings);
}
if (null == workingPath || workingPath.isEmpty()) {
workingPath = context.getModuleDirPath(); // Last ditch effort. Location of the .iml
}
return null == workingPath ? "" : workingPath;
}
@Nonnull
private static VirtualFile createTemporalFile(@javax.annotation.Nullable Project project,
@Nonnull String prefix,
@Nonnull String suffix,
@Nonnull byte[] content) throws IOException {
File tempFile = FileUtil.createTempFile(PathUtil.suggestFileName(prefix + "_", true, false),
PathUtil.suggestFileName("_" + suffix, true, false), true);
if (content.length != 0) {
FileUtil.writeToFile(tempFile, content);
}
if (!tempFile.setWritable(false, false)) LOG.warn("Can't set writable attribute of temporal file");
VirtualFile file = VfsUtil.findFileByIoFile(tempFile, true);
if (file == null) {
throw new IOException("Can't create temp file for revision content");
}
VfsUtil.markDirtyAndRefresh(true, true, true, file);
return file;
}
@Override
@Nonnull
public VirtualFile createFile(String targetPath) {
final String path = PathUtil.getParentPath(targetPath);
final String name = PathUtil.getFileName(targetPath);
return ApplicationManager.getApplication().runWriteAction(new Computable<VirtualFile>() {
@Override
public VirtualFile compute() {
try {
VirtualFile targetDir = findOrCreateDir(path);
return targetDir.createChildData(this, name);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public PsiFile addFileToProject(@NonNls String rootPath, @NonNls final String relativePath, @NonNls final String fileText) throws IOException {
final VirtualFile dir = VfsUtil.createDirectories(rootPath + "/" + PathUtil.getParentPath(relativePath));
final VirtualFile[] virtualFile = new VirtualFile[1];
new WriteCommandAction.Simple(getProject()) {
@Override
protected void run() throws Throwable {
virtualFile[0] = dir.createChildData(this, StringUtil.getShortName(relativePath, '/'));
VfsUtil.saveText(virtualFile[0], fileText);
}
}.execute();
return ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
public PsiFile compute() {
return PsiManager.getInstance(getProject()).findFile(virtualFile[0]);
}
});
}
@Override
public boolean browseUsingPath(@Nullable final String url,
@Nullable String browserPath,
@Nullable final WebBrowser browser,
@Nullable final Project project,
@Nonnull final String[] additionalParameters) {
Runnable launchTask = null;
if (browserPath == null && browser != null) {
browserPath = PathUtil.toSystemDependentName(browser.getPath());
launchTask = new Runnable() {
@Override
public void run() {
browseUsingPath(url, null, browser, project, additionalParameters);
}
};
}
return doLaunch(url, browserPath, browser, project, additionalParameters, launchTask);
}
@Override
public CompositePackagingElement<?> createComposite(CompositePackagingElement<?> parent,
@Nullable String baseName,
@Nonnull ArtifactEditorContext context) {
final String initialValue = PackagingElementFactoryImpl.suggestFileName(parent, baseName != null ? baseName : "archive", ".zip");
String path =
Messages.showInputDialog(context.getProject(), "Enter archive name: ", "New Archive", null, initialValue, new FilePathValidator());
if (path == null) {
return null;
}
path = FileUtil.toSystemIndependentName(path);
final String parentPath = PathUtil.getParentPath(path);
final String fileName = PathUtil.getFileName(path);
final PackagingElement<?> element = new ZipArchivePackagingElement(fileName);
return (CompositePackagingElement<?>)PackagingElementFactory.getInstance(context.getProject()).createParentDirectories(parentPath, element);
}
@Override
public CompositePackagingElement<?> createComposite(CompositePackagingElement<?> parent,
String baseName,
@Nonnull ArtifactEditorContext context) {
final String initialValue = PackagingElementFactoryImpl.suggestFileName(parent, baseName != null ? baseName : "folder", "");
String path = Messages
.showInputDialog(context.getProject(), "Enter directory name: ", "New Directory", null, initialValue, new FilePathValidator());
if (path == null) {
return null;
}
path = FileUtil.toSystemIndependentName(path);
final String parentPath = PathUtil.getParentPath(path);
final String fileName = PathUtil.getFileName(path);
final PackagingElement<?> element = new DirectoryPackagingElement(fileName);
return (CompositePackagingElement<?>)PackagingElementFactoryImpl.getInstance(context.getProject()).createParentDirectories(parentPath, element);
}
@Nonnull
public static String getPresentableName(@Nonnull Library library) {
final String name = library.getName();
if (name != null) {
return name;
}
if (library instanceof LibraryEx && ((LibraryEx)library).isDisposed()) {
return "Disposed Library";
}
String[] urls = library.getUrls(BinariesOrderRootType.getInstance());
if (urls.length > 0) {
return PathUtil.getFileName(VfsUtilCore.urlToPath(urls[0]));
}
return "Empty Library";
}
public static String getRelativeFileUrl(Project project, VirtualFile virtualFile) {
if (project == null || virtualFile == null) {
return null;
}
String url = virtualFile.getUserData(RELATIVE_FILE_URL);
if (url == null && project.getBasePath() != null) {
String projectDir = PathUtil.getLocalPath(project.getBasePath());
url = PathUtil.getLocalPath(virtualFile.getPath())
.replaceFirst("^" + Pattern.quote(projectDir), "");
virtualFile.putUserData(RELATIVE_FILE_URL, url);
}
return url;
}
@Nullable
private static LightVirtualFile createSnapshot(@NotNull Script script) {
// LightVirtualFiles have no parent directory, so just use the filename.
final String filename = PathUtil.getFileName(script.getUri());
final String scriptSource = script.getSource();
if (scriptSource == null) {
return null;
}
final LightVirtualFile snapshot = new LightVirtualFile(filename, DartFileType.INSTANCE, scriptSource);
snapshot.setWritable(false);
return snapshot;
}
String getBaseName() {
// Virtual test that represents loading or compiling a test suite. See lib/src/runner/loader.dart -> Loader.loadFile() in pkg/test source code
if (this instanceof Test && getParent() == null) {
if (myName.startsWith(LOADING_PREFIX)) {
return LOADING_PREFIX + PathUtil.getFileName(myName.substring(LOADING_PREFIX.length()));
}
else if (myName.startsWith(COMPILING_PREFIX)) {
return COMPILING_PREFIX + PathUtil.getFileName(myName.substring(COMPILING_PREFIX.length()));
}
return myName; // can't happen
}
// file-level group
if (this instanceof Group && NO_NAME.equals(myName) && myParent == null && hasSuite()) {
return PathUtil.getFileName(getSuite().getPath());
}
// top-level group in suite
if (this instanceof Group && myParent != null && myParent.getParent() == null && NO_NAME.equals(myParent.getName())) {
return myName;
}
if (hasValidParent()) {
final String parentName = getParent().getName();
if (myName.startsWith(parentName + " ")) {
return myName.substring(parentName.length() + 1);
}
}
return myName;
}
@Nullable
private static LightVirtualFile createSnapshot(@NotNull Script script) {
// LightVirtualFiles have no parent directory, so just use the filename.
final String filename = PathUtil.getFileName(script.getUri());
final String scriptSource = script.getSource();
if (scriptSource == null) {
return null;
}
final LightVirtualFile snapshot = new LightVirtualFile(filename, DartFileType.INSTANCE, scriptSource);
snapshot.setWritable(false);
return snapshot;
}
@Override
public String getDisplayName() {
String name = myLibrary.getName();
if (name == null) {
String[] urls = myLibrary.getUrls(BinariesOrderRootType.getInstance());
if (urls.length > 0) {
name = PathUtil.getFileName(VfsUtilCore.urlToPath(urls[0]));
}
else {
name = "empty";
}
}
return "Library '" + name + "'";
}
@SuppressWarnings("Duplicates")
private static String findTestDataPath() {
if (new File(PathManager.getHomePath() + "/contrib").isDirectory()) {
// started from IntelliJ IDEA Ultimate project
return FileUtil.toSystemIndependentName(PathManager.getHomePath() + "/contrib/Dart/testData");
}
final File f = new File("testData");
if (f.isDirectory()) {
// started from 'Dart-plugin' project
return FileUtil.toSystemIndependentName(f.getAbsolutePath());
}
final String parentPath = PathUtil.getParentPath(PathManager.getHomePath());
if (new File(parentPath + "/intellij-plugins").isDirectory()) {
// started from IntelliJ IDEA Community Edition + Dart Plugin project
return FileUtil.toSystemIndependentName(parentPath + "/intellij-plugins/Dart/testData");
}
if (new File(parentPath + "/contrib").isDirectory()) {
// started from IntelliJ IDEA Community + Dart Plugin project
return FileUtil.toSystemIndependentName(parentPath + "/contrib/Dart/testData");
}
return "";
}
@Nullable
public static VirtualFile getProjectBaseDir(@Nullable Project project) {
if (project == null) {
return null;
}
final String basePath = PathUtil.toSystemIndependentName(project.getBasePath());
if (basePath == null) {
return null;
}
return LocalFileSystem.getInstance().findFileByPath(basePath);
}
@Nullable
@Override
protected GenfilesPath parseItem(ProjectViewParser parser, ParseContext parseContext) {
String canonicalPath = PathUtil.getCanonicalPath(parseContext.current().text);
List<BlazeValidationError> errors = new ArrayList<>();
if (!GenfilesPath.validate(canonicalPath, errors)) {
parseContext.addErrors(errors);
return null;
}
return new GenfilesPath(canonicalPath);
}