Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Cross-Platform File Operations

БесплатноБез исполняемых скриптовНе проверен

Handle file operations correctly across macOS, Windows, and Linux

drewipsonот drewipson★ 26 звёзд на GitHub13 установок в других каталогах

Об этом скилле

Cross-Platform File Operations Skill

This skill provides expertise in handling file system operations that work correctly across all major operating systems: macOS, Windows, and Linux.

Platform Differences

Path Separators

  • Windows: Uses backslash \ (e.g., C:\Users\name\file.txt)
  • macOS/Linux: Uses forward slash / (e.g., /Users/name/file.txt)

Home Directory

  • Windows: C:\Users\username (via %USERPROFILE%)
  • macOS: /Users/username (via $HOME)
  • Linux: /home/username (via $HOME)

Line Endings

  • Windows: CRLF (\r\n)
  • macOS/Linux: LF (\n)

File System Case Sensitivity

  • Windows: Case-insensitive (file.txt = FILE.TXT)
  • macOS: Case-insensitive by default (configurable to case-sensitive)
  • Linux: Case-sensitive (file.txt ≠ FILE.TXT)

Safe Path Operations

Always Use path Module

import * as path from 'path';

// Good - works everywhere
const configPath = path.join(homeDir, '.claude', 'settings.json');

// Bad - breaks on Windows
const configPath = `${homeDir}/.claude/settings.json`;

Path Methods

// Join path segments
path.join('a', 'b', 'c')  // 'a/b/c' on Unix, 'a\b\c' on Windows

// Normalize path (resolve '..' and '.')
path.normalize('/foo/bar/../baz')  // '/foo/baz'

// Get directory name
path.dirname('/foo/bar/file.txt')  // '/foo/bar'

// Get file name
path.basename('/foo/bar/file.txt')  // 'file.txt'

// Get file extension
path.extname('file.txt')  // '.txt'

// Parse path into components
path.parse('/foo/bar/file.txt')
// {
//   root: '/',
//   dir: '/foo/bar',
//   base: 'file.txt',
//   ext: '.txt',
//   name: 'file'
// }

// Resolve absolute path
path.resolve('foo', 'bar', 'baz')  // Absolute path from cwd

// Check if path is absolute
path.isAbsolute('/foo/bar')  // true
path.isAbsolute('foo/bar')   // false

Home Directory Resolution

import * as os from 'os';

/**
 * Get user home directory (cross-platform)
 */
function getHomeDirectory(): string {
  // Preferred method (Node.js built-in)
  return os.homedir();

  // Alternative using environment variables
  // return process.env.HOME || process.env.USERPROFILE || os.homedir();
}

/**
 * Get Claude global config directory
 */
function getClaudeGlobalPath(): string {
  return path.join(getHomeDirectory(), '.claude');
}

// Usage
const globalSettingsPath = path.join(getClaudeGlobalPath(), 'settings.json');

Async File Operations

Always use async to avoid blocking the extension host:

import * as fs from 'fs/promises';

// Read file
async function readFile(filePath: string): Promise<string> {
  try {
    return await fs.readFile(filePath, 'utf-8');
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
      throw new Error(`File not found: ${filePath}`);
    }
    throw error;
  }
}

// Write file (create directories if needed)
async function writeFile(filePath: string, content: string): Promise<void> {
  const dir = path.dirname(filePath);
  await fs.mkdir(dir, { recursive: true });
  await fs.writeFile(filePath, content, 'utf-8');
}

// Check if file exists
async function fileExists(filePath: string): Promise<boolean> {
  try {
    await fs.access(filePath);
    return true;
  } catch {
    return false;
  }
}

// Check if path is directory
async function isDirectory(dirPath: string): Promise<boolean> {
  try {
    const stats = await fs.stat(dirPath);
    return stats.isDirectory();
  } catch {
    return false;
  }
}

// Delete file
async function deleteFile(filePath: string): Promise<void> {
  try {
    await fs.unlink(filePath);
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
      throw error;
    }
    // File doesn't exist, ignore
  }
}

// Delete directory recursively
async function deleteDirectory(dirPath: string): Promise<void> {
  await fs.rm(dirPath, { recursive: true, force: true });
}

Directory Operations

// List directory contents
async function listDirectory(dirPath: string): Promise<string[]> {
  const entries = await fs.readdir(dirPath);
  return entries;
}

// List with file info
async function listDirectoryDetailed(dirPath: string): Promise<fs.Dirent[]> {
  const entries = await fs.readdir(dirPath, { withFileTypes: true });
  return entries;
}

// Recursive file discovery
async function findFiles(
  dirPath: string,
  pattern: RegExp
): Promise<string[]> {
  const results: string[] = [];

  async function scan(currentPath: string) {
    try {
      const entries = await fs.readdir(currentPath, { withFileTypes: true });

      for (const entry of entries) {
        const fullPath = path.join(currentPath, entry.name);

        if (entry.isDirectory()) {
          await scan(fullPath);
        } else if (entry.isFile() && pattern.test(entry.name)) {
          results.push(fullPath);
        }
      }
    } catch (error) {
      // Handle permission errors gracefully
Полный SKILL.md на GitHub

Установить Cross-Platform File Operations в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл Cross-Platform File Operations?

Handle file operations correctly across macOS, Windows, and Linux

Как установить скилл Cross-Platform File Operations?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Cross-Platform File Operations запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Cross-Platform File Operations с