Java Code Examples for com.intellij.openapi.util.SystemInfo#isUnix()

The following examples show how to use com.intellij.openapi.util.SystemInfo#isUnix() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SystemHealthMonitor.java    From consulo with Apache License 2.0 7 votes vote down vote up
private void checkSignalBlocking() {
  if (SystemInfo.isUnix && JnaLoader.isLoaded()) {
    try {
      LibC lib = Native.loadLibrary("c", LibC.class);
      Memory buf = new Memory(1024);
      if (lib.sigaction(LibC.SIGINT, null, buf) == 0) {
        long handler = Native.POINTER_SIZE == 8 ? buf.getLong(0) : buf.getInt(0);
        if (handler == LibC.SIG_IGN) {
          showNotification(new KeyHyperlinkAdapter("ide.sigint.ignored.message"));
        }
      }
    }
    catch (Throwable t) {
      LOG.warn(t);
    }
  }
}
 
Example 2
Source File: ReactiveTfvcClientHost.java    From azure-devops-intellij with MIT License 6 votes vote down vote up
@NotNull
private static GeneralCommandLine getClientCommandLine(
        Path clientExecutable,
        int protocolPort,
        Path logDirectory,
        Path clientHome) {
    ArrayList<String> command = Lists.newArrayList(
            clientExecutable.toString(),
            Integer.toString(protocolPort),
            logDirectory.toString(),
            REACTIVE_CLIENT_LOG_LEVEL);
    if (SystemInfo.isUnix) {
        // Client executable is a shell script on Unix-like operating systems
        command.addAll(0, Arrays.asList("/usr/bin/env", "sh"));
    }

    return new GeneralCommandLine(command).withWorkDirectory(clientHome.toString());
}
 
Example 3
Source File: FileWatcherTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testUnicodePaths() throws Exception {
  if (!SystemInfo.isUnix || SystemInfo.isMac) {
    System.err.println("Ignored: well-defined FS required");
    return;
  }

  File topDir = createTestDir("top");
  File testDir = createTestDir(topDir, "тест");
  File testFile = createTestFile(testDir, "файл.txt");
  refresh(topDir);

  LocalFileSystem.WatchRequest request = watch(topDir);
  try {
    myAccept = true;
    FileUtil.writeToFile(testFile, "abc");
    assertEvent(VFileContentChangeEvent.class, testFile.getPath());
  }
  finally {
    unwatch(request);
  }
}
 
Example 4
Source File: OSProcessManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public boolean killProcessTree(@Nonnull Process process) {
  if (SystemInfo.isWindows) {
    try {
      WinProcess winProcess = createWinProcess(process);
      winProcess.killRecursively();
      return true;
    }
    catch (Throwable e) {
      LOG.info("Cannot kill process tree", e);
    }
  }
  else if (SystemInfo.isUnix) {
    return UnixProcessManager.sendSigKillToProcessTree(process);
  }
  return false;
}
 
Example 5
Source File: LocalFileSystemTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void testBadFileName() throws Exception {
  if (!SystemInfo.isUnix) {
    System.err.println(getName() + " skipped: " + SystemInfo.OS_NAME);
    return;
  }

  final File dir = FileUtil.createTempDirectory("test.", ".dir");
  final File file = FileUtil.createTempFile(dir, "test\\", "\\txt", true);

  final VirtualFile vDir = myFS.refreshAndFindFileByIoFile(dir);
  assertNotNull(vDir);
  assertEquals(0, vDir.getChildren().length);

  ((VirtualFileSystemEntry)vDir).markDirtyRecursively();
  vDir.refresh(false, true);

  final VirtualFile vFile = myFS.refreshAndFindFileByIoFile(file);
  assertNull(vFile);
}
 
Example 6
Source File: OSProcessUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static int getProcessID(@Nonnull Process process) {
  if (SystemInfo.isWindows) {
    try {
      if (process instanceof WinPtyProcess) {
        return ((WinPtyProcess)process).getChildProcessId();
      }
      return WinProcessManager.getProcessId(process);
    }
    catch (Throwable e) {
      throw new IllegalStateException("Cannot get PID from instance of " + process.getClass() + ", OS: " + SystemInfo.OS_NAME, e);
    }
  }
  else if (SystemInfo.isUnix) {
    return UnixProcessManager.getProcessId(process);
  }
  throw new IllegalStateException("Unknown OS: " + SystemInfo.OS_NAME);
}
 
Example 7
Source File: RunnerMediator.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Destroys process tree: in case of windows via imitating ctrl+c, in case of unix via sending sig_int to every process in tree.
 * @param process to kill with all sub-processes.
 */
static boolean destroyProcess(@Nonnull final Process process, final boolean softKill) {
  try {
    if (SystemInfo.isWindows) {
      sendCtrlEventThroughStream(process, softKill ? C : BRK);
      return true;
    }
    else if (SystemInfo.isUnix) {
      if (softKill) {
        return UnixProcessManager.sendSigIntToProcessTree(process);
      }
      else {
        return UnixProcessManager.sendSigKillToProcessTree(process);
      }
    }
    else {
      return false;
    }
  }
  catch (Exception e) {
    LOG.error("Couldn't terminate the process", e);
    return false;
  }
}
 
Example 8
Source File: VMWarePropertiesReader.java    From teamcity-vmware-plugin with Apache License 2.0 5 votes vote down vote up
@Nullable
private static String getToolPath(@NotNull final BuildAgentConfiguration configuration) {
  final String rpctoolPath = TeamCityProperties.getProperty(RPC_TOOL_PARAMETER);
  if (StringUtil.isNotEmpty(rpctoolPath)){
    return rpctoolPath;
  }

  if (SystemInfo.isUnix) { // Linux, MacOSX, FreeBSD
    final Map<String, String> envs = configuration.getBuildParameters().getEnvironmentVariables();
    final String path = envs.get("PATH");
    if (path != null) for (String p : StringUtil.splitHonorQuotes(path, File.pathSeparatorChar)) {
      final File file = new File(p, VMWARE_RPCTOOL_NAME);
      if (file.exists()) {
        return file.getAbsolutePath();
      }
    }
  }
  if (SystemInfo.isLinux) {
    return getExistingCommandPath(LINUX_COMMANDS);
  } else if (SystemInfo.isWindows) {
    return getExistingCommandPath(WINDOWS_COMMANDS);
  } else if (SystemInfo.isMac) {
    return getExistingCommandPath(MAC_COMMANDS);
  } else {
    return getExistingCommandPath(LINUX_COMMANDS); //todo: update for other OS'es
  }
}
 
Example 9
Source File: LocalFileSystemTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void testHardLinks() throws Exception {
  if (!SystemInfo.isWindows && !SystemInfo.isUnix) {
    System.err.println(getName() + " skipped: " + SystemInfo.OS_NAME);
    return;
  }

  final boolean safeWrite = GeneralSettings.getInstance().isUseSafeWrite();
  final File dir = FileUtil.createTempDirectory("hardlinks.", ".dir", false);
  final SafeWriteRequestor requestor = new SafeWriteRequestor() {
  };
  try {
    GeneralSettings.getInstance().setUseSafeWrite(false);

    final File targetFile = new File(dir, "targetFile");
    assertTrue(targetFile.createNewFile());
    final File hardLinkFile = IoTestUtil.createHardLink(targetFile.getAbsolutePath(), "hardLinkFile");

    final VirtualFile file = myFS.refreshAndFindFileByIoFile(targetFile);
    assertNotNull(file);
    file.setBinaryContent("hello".getBytes(CharsetToolkit.UTF8_CHARSET), 0, 0, requestor);
    assertTrue(file.getLength() > 0);

    final VirtualFile check = myFS.refreshAndFindFileByIoFile(hardLinkFile);
    assertNotNull(check);
    assertEquals(file.getLength(), check.getLength());
    assertEquals("hello", VfsUtilCore.loadText(check));
  }
  finally {
    GeneralSettings.getInstance().setUseSafeWrite(safeWrite);
    FileUtil.delete(dir);
  }
}
 
Example 10
Source File: FileUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("Duplicates")
private static void performCopy(@Nonnull File fromFile, @Nonnull File toFile, final boolean syncTimestamp) throws IOException {
  if (filesEqual(fromFile, toFile)) return;
  final FileOutputStream fos = openOutputStream(toFile);

  try {
    final FileInputStream fis = new FileInputStream(fromFile);
    try {
      copy(fis, fos);
    }
    finally {
      fis.close();
    }
  }
  finally {
    fos.close();
  }

  if (syncTimestamp) {
    final long timeStamp = fromFile.lastModified();
    if (timeStamp < 0) {
      LOG.warn("Invalid timestamp " + timeStamp + " of '" + fromFile + "'");
    }
    else if (!toFile.setLastModified(timeStamp)) {
      LOG.warn("Unable to set timestamp " + timeStamp + " to '" + toFile + "'");
    }
  }

  if (SystemInfo.isUnix && fromFile.canExecute()) {
    FileSystemUtil.clonePermissionsToExecute(fromFile.getPath(), toFile.getPath());
  }
}
 
Example 11
Source File: KillableProcessHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * This method shouldn't be overridden, see shouldKillProcessSoftly
 */
private boolean canKillProcessSoftly() {
  if (processCanBeKilledByOS(myProcess)) {
    if (SystemInfo.isWindows) {
      // runnerw.exe can send Ctrl+C events to a wrapped process
      return myMediatedProcess;
    }
    else if (SystemInfo.isUnix) {
      // 'kill -SIGINT <pid>' will be executed
      return true;
    }
  }
  return false;
}
 
Example 12
Source File: KillableProcessHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected boolean destroyProcessGracefully() {
  if (SystemInfo.isWindows && myMediatedProcess) {
    return RunnerMediator.destroyProcess(myProcess, true);
  }
  else if (SystemInfo.isUnix) {
    return UnixProcessManager.sendSigIntToProcessTree(myProcess);
  }
  return false;
}
 
Example 13
Source File: ReadonlyStatusIsVisibleActivationCheck.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void check(final Project project, final String vcsName) {
  if (SystemInfo.isUnix && "root".equals(System.getenv("USER"))) {
    Notifications.Bus.notify(new Notification(vcsName, vcsName + ": can not see read-only status",
        "You are logged as <b>root</b>, that's why:<br><br>- " + ApplicationNamesInfo.getInstance().getFullProductName() + " can not see read-only status of files.<br>" +
        "- All files are treated as writeable.<br>- Automatic file checkout on modification is impossible.", NotificationType.WARNING), project);
  }
}
 
Example 14
Source File: FileUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Contract("null,_ -> null; !null,_ -> !null")
public static String getLocationRelativeToUserHome(@Nullable String path, boolean unixOnly) {
  if (path == null) return null;

  if (SystemInfo.isUnix || !unixOnly) {
    File projectDir = new File(path);
    File userHomeDir = new File(SystemProperties.getUserHome());
    if (isAncestor(userHomeDir, projectDir, true)) {
      return '~' + File.separator + getRelativePath(userHomeDir, projectDir);
    }
  }

  return path;
}
 
Example 15
Source File: LocalFileSystemBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public String getCanonicallyCasedName(@Nonnull VirtualFile file) {
  if (isCaseSensitive()) {
    return super.getCanonicallyCasedName(file);
  }

  String originalFileName = file.getName();
  long t = LOG.isTraceEnabled() ? System.nanoTime() : 0;
  try {
    File ioFile = convertToIOFile(file);

    File canonicalFile = ioFile.getCanonicalFile();
    String canonicalFileName = canonicalFile.getName();
    if (!SystemInfo.isUnix) {
      return canonicalFileName;
    }

    // linux & mac support symbolic links
    // unfortunately canonical file resolves sym links
    // so its name may differ from name of origin file
    //
    // Here FS is case sensitive, so let's check that original and
    // canonical file names are equal if we ignore name case
    if (canonicalFileName.compareToIgnoreCase(originalFileName) == 0) {
      // p.s. this should cover most cases related to not symbolic links
      return canonicalFileName;
    }

    // Ok, names are not equal. Let's try to find corresponding file name
    // among original file parent directory
    File parentFile = ioFile.getParentFile();
    if (parentFile != null) {
      // I hope ls works fast on Unix
      String[] canonicalFileNames = parentFile.list();
      if (canonicalFileNames != null) {
        for (String name : canonicalFileNames) {
          // if names are equals
          if (name.compareToIgnoreCase(originalFileName) == 0) {
            return name;
          }
        }
      }
    }
    // No luck. So ein mist!
    // Ok, garbage in, garbage out. We may return original or canonical name
    // no difference. Let's return canonical name just to preserve previous
    // behaviour of this code.
    return canonicalFileName;
  }
  catch (IOException | InvalidPathException e) {
    return originalFileName;
  }
  finally {
    if (t != 0) {
      t = (System.nanoTime() - t) / 1000;
      LOG.trace("getCanonicallyCasedName(" + file + "): " + t + " mks");
    }
  }
}
 
Example 16
Source File: CreateDesktopEntryAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean isAvailable() {
  return SystemInfo.isUnix && SystemInfo.hasXdgOpen();
}
 
Example 17
Source File: UnixProcessManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static void checkCLib() {
  if (C_LIB == null) {
    throw new IllegalStateException("Couldn't load c library, OS: " + SystemInfo.OS_NAME + ", isUnix: " + SystemInfo.isUnix);
  }
}
 
Example 18
Source File: FileElement.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static boolean isFileHidden(@Nullable VirtualFile file) {
  return file != null &&
         file.isValid() &&
         file.isInLocalFileSystem() &&
         (file.is(VFileProperty.HIDDEN) || SystemInfo.isUnix && file.getName().startsWith("."));
}
 
Example 19
Source File: LocalFileSystemTest.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void testFindRoot() throws IOException {
  VirtualFile root = myFS.findFileByPath("wrong_path");
  assertNull(root);

  VirtualFile root2;
  if (SystemInfo.isWindows) {
    root = myFS.findFileByPath("\\\\unit-133");
    assertNotNull(root);
    root2 = myFS.findFileByPath("//UNIT-133");
    assertNotNull(root2);
    assertEquals(String.valueOf(root2), root, root2);
    RefreshQueue.getInstance().processSingleEvent(new VFileDeleteEvent(this, root, false));

    root = myFS.findFileByIoFile(new File("\\\\unit-133"));
    assertNotNull(root);
    RefreshQueue.getInstance().processSingleEvent(new VFileDeleteEvent(this, root, false));

    if (new File("c:").exists()) {
      root = myFS.findFileByPath("c:");
      assertNotNull(root);
      assertEquals("C:/", root.getPath());

      root2 = myFS.findFileByPath("C:\\");
      assertSame(String.valueOf(root), root, root2);

      VirtualFileManager fm = VirtualFileManager.getInstance();
      root = fm.findFileByUrl("file://C:/");
      assertNotNull(root);
      root2 = fm.findFileByUrl("file:///c:/");
      assertSame(String.valueOf(root), root, root2);
    }
  }
  else if (SystemInfo.isUnix) {
    root = myFS.findFileByPath("/");
    assertNotNull(root);
    assertEquals(root.getPath(), "/");
  }

  root = myFS.findFileByPath("");
  assertNotNull(root);

  File jarFile = IoTestUtil.createTestJar();
  root = VirtualFileManager.getInstance().findFileByUrl("jar://" + jarFile.getPath() + "!/");
  assertNotNull(root);

  root2 = VirtualFileManager.getInstance().findFileByUrl("jar://" + jarFile.getPath().replace(File.separator, "//") + "!/");
  assertEquals(String.valueOf(root2), root, root2);

  if (!SystemInfo.isFileSystemCaseSensitive) {
    root2 = VirtualFileManager.getInstance().findFileByUrl("jar://" + jarFile.getPath().toUpperCase(Locale.US) + "!/");
    assertEquals(String.valueOf(root2), root, root2);
  }
}
 
Example 20
Source File: FileWatcherTest.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void testSwitchingToFsRoot() throws Exception {
  File topDir = createTestDir("top");
  File rootDir = createTestDir(topDir, "root");
  File file1 = createTestFile(topDir, "1.txt");
  File file2 = createTestFile(rootDir, "2.txt");
  refresh(topDir);

  File fsRoot = new File(SystemInfo.isUnix ? "/" : topDir.getPath().substring(0, topDir.getPath().indexOf(File.separatorChar)) + "\\");
  assertTrue("can't guess root of " + topDir, fsRoot.exists());

  LocalFileSystem.WatchRequest request = watch(rootDir);
  try {
    myAccept = true;
    FileUtil.writeToFile(file1, "abc");
    FileUtil.writeToFile(file2, "abc");
    assertEvent(VFileContentChangeEvent.class, file2.getPath());

    LocalFileSystem.WatchRequest rootRequest = watch(fsRoot);
    try {
      myTimeout = 10 * INTER_RESPONSE_DELAY;
      myAccept = true;
      FileUtil.writeToFile(file1, "12345");
      FileUtil.writeToFile(file2, "12345");
      assertEvent(VFileContentChangeEvent.class, file1.getPath(), file2.getPath());
      myTimeout = NATIVE_PROCESS_DELAY;
    }
    finally {
      unwatch(rootRequest);
    }

    myAccept = true;
    FileUtil.writeToFile(file1, "");
    FileUtil.writeToFile(file2, "");
    assertEvent(VFileContentChangeEvent.class, file2.getPath());
  }
  finally {
    unwatch(request);
  }

  myTimeout = 10 * INTER_RESPONSE_DELAY;
  myAccept = true;
  FileUtil.writeToFile(file1, "xyz");
  FileUtil.writeToFile(file2, "xyz");
  assertEvent(VFileEvent.class);
  myTimeout = NATIVE_PROCESS_DELAY;
}