Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
Expand Down
77 changes: 77 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
name: CI

on:
push:
pull_request:

permissions:
contents: read

concurrency:
group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }}
cancel-in-progress: true

jobs:
test:
name: Lint, test and build (Node ${{ matrix.node }})
runs-on: ubuntu-latest
strategy:
matrix:
node: [18, 22, 24]
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v5
with:
node-version: ${{ matrix.node }}
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm lint
- run: pnpm test
- run: pnpm build

e2e:
name: End-to-end on macOS
runs-on: macos-latest
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v5
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile

- name: Install the packed CLI globally
run: |
npm pack
npm install --global ./hide-files-*.tgz
hide-files --version

- name: Hide and unhide the items on a test Desktop
run: |
export HOME="$RUNNER_TEMP/home"
desktop="$HOME/Desktop"
mkdir -p "$desktop/My Folder"
touch "$desktop/Screenshot 1.png" "$desktop/\$(echo pwned).txt" "$desktop/.DS_Store"

flags() { /usr/bin/stat -f '%Sf' "$1"; }

hide-files hide
for item in "$desktop"/*; do
[[ "$(flags "$item")" == *hidden* ]] || { echo "::error::Not hidden: $item"; exit 1; }
done
[[ "$(flags "$desktop/.DS_Store")" != *hidden* ]] || { echo "::error::Dotfile was hidden"; exit 1; }

hide-files unhide
for item in "$desktop"/*; do
[[ "$(flags "$item")" != *hidden* ]] || { echo "::error::Still hidden: $item"; exit 1; }
done

- name: Exit non-zero when the Desktop folder is missing
run: |
export HOME="$RUNNER_TEMP/no-home"
if hide-files hide; then
echo "::error::Expected hide-files to fail without a Desktop folder"
exit 1
fi
2 changes: 1 addition & 1 deletion bin/hide-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@

import { program } from '../src'

program.parse()
program.parseAsync()
87 changes: 87 additions & 0 deletions src/desktop.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import {
afterEach,
beforeEach,
describe,
expect,
it,
jest,
} from '@jest/globals'
import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'
import { Run, setHidden } from './desktop'

describe('setHidden', () => {
let dir: string
let run: jest.Mock<Run>

beforeEach(async () => {
dir = await mkdtemp(join(tmpdir(), 'hide-files-'))
run = jest.fn<Run>().mockResolvedValue(undefined)
})

afterEach(async () => {
await rm(dir, { recursive: true, force: true })
})

it('passes every visible item to chflags without shell quoting', async () => {
const names = ['Screenshot 1.png', 'My Folder', `$HOME "quoted" 'it'.txt`]
await writeFile(join(dir, names[0]), '')
await mkdir(join(dir, names[1]))
await writeFile(join(dir, names[2]), '')

await expect(setHidden(dir, true, run)).resolves.toBe(3)

expect(run).toHaveBeenCalledTimes(1)
const [file, [flag, ...paths]] = run.mock.calls[0]
expect(file).toBe('chflags')
expect(flag).toBe('hidden')
expect(paths.sort()).toEqual(names.map((name) => join(dir, name)).sort())
})

it('clears the flag when unhiding', async () => {
await writeFile(join(dir, 'notes.txt'), '')

await setHidden(dir, false, run)

expect(run).toHaveBeenCalledWith('chflags', [
'nohidden',
join(dir, 'notes.txt'),
])
})

it('leaves dotfiles alone', async () => {
await writeFile(join(dir, '.DS_Store'), '')
await writeFile(join(dir, '.localized'), '')
await writeFile(join(dir, 'notes.txt'), '')

await setHidden(dir, true, run)

expect(run).toHaveBeenCalledWith('chflags', [
'hidden',
join(dir, 'notes.txt'),
])
})

it('does not run chflags when there is nothing to change', async () => {
await writeFile(join(dir, '.DS_Store'), '')

await expect(setHidden(dir, true, run)).resolves.toBe(0)
expect(run).not.toHaveBeenCalled()
})

it('rejects when chflags fails', async () => {
await writeFile(join(dir, 'notes.txt'), '')
const error = new Error('Command failed')
run.mockRejectedValue(error)

await expect(setHidden(dir, true, run)).rejects.toBe(error)
})

it('rejects when the directory does not exist', async () => {
await expect(
setHidden(join(dir, 'missing'), true, run),
).rejects.toMatchObject({ code: 'ENOENT' })
expect(run).not.toHaveBeenCalled()
})
})
39 changes: 39 additions & 0 deletions src/desktop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { execFile } from 'child_process'
import { readdir } from 'fs/promises'
import { homedir } from 'os'
import { join } from 'path'
import { promisify } from 'util'

export type Run = (file: string, args: string[]) => Promise<unknown>

const execFileAsync: Run = promisify(execFile)

export function getDesktopPath() {
return join(homedir(), 'Desktop')
}

/**
* Sets or clears the macOS `hidden` flag on every item in `dir`. Dotfiles are
* skipped, like the shell's `*` glob, so `.DS_Store` and friends are untouched.
*
* `chflags` is called without a shell, so paths are passed through as-is no
* matter which characters they contain.
*
* @returns the number of items whose flag was changed
*/
export async function setHidden(
dir: string,
hidden: boolean,
run: Run = execFileAsync,
) {
const names = (await readdir(dir)).filter((name) => !name.startsWith('.'))
if (names.length === 0) {
return 0
}

await run('chflags', [
hidden ? 'hidden' : 'nohidden',
...names.map((name) => join(dir, name)),
])
return names.length
}
135 changes: 135 additions & 0 deletions src/program.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import {
afterEach,
beforeEach,
describe,
expect,
it,
jest,
} from '@jest/globals'
import { readFileSync } from 'fs'
import { join } from 'path'
import { getDesktopPath, setHidden } from './desktop'
import { program } from './program'

jest.mock('./desktop')

const desktopPath = '/Users/test/Desktop'
const originalPlatform = process.platform

function setPlatform(platform: NodeJS.Platform) {
Object.defineProperty(process, 'platform', { value: platform })
}

function cli(...args: string[]) {
return program.parseAsync(args, { from: 'user' })
}

describe('program', () => {
let log: jest.SpiedFunction<typeof console.log>
let error: jest.SpiedFunction<typeof console.error>

beforeEach(() => {
setPlatform('darwin')
jest.mocked(getDesktopPath).mockReturnValue(desktopPath)
jest.mocked(setHidden).mockResolvedValue(2)
log = jest.spyOn(console, 'log').mockImplementation(() => undefined)
error = jest.spyOn(console, 'error').mockImplementation(() => undefined)
})

afterEach(() => {
setPlatform(originalPlatform)
process.exitCode = undefined
jest.resetAllMocks()
jest.restoreAllMocks()
})

it('prints the package version', async () => {
const pkg = JSON.parse(
readFileSync(join(__dirname, '..', 'package.json'), 'utf8'),
)
const writeOut = jest.fn<(str: string) => void>()
program.exitOverride().configureOutput({ writeOut })

await expect(cli('--version')).rejects.toMatchObject({
code: 'commander.version',
})
expect(writeOut).toHaveBeenCalledWith(`${pkg.version}\n`)
})

it('hides the Desktop items', async () => {
await cli('hide')

expect(setHidden).toHaveBeenCalledWith(desktopPath, true)
expect(log).toHaveBeenCalledWith(expect.stringContaining('hidden!'))
expect(process.exitCode).toBeUndefined()
})

it('unhides the Desktop items', async () => {
await cli('unhide')

expect(setHidden).toHaveBeenCalledWith(desktopPath, false)
expect(log).toHaveBeenCalledWith(expect.stringContaining('shown!'))
expect(process.exitCode).toBeUndefined()
})

it('says so when the Desktop has nothing to hide', async () => {
jest.mocked(setHidden).mockResolvedValue(0)

await cli('hide')

expect(log).toHaveBeenCalledWith(
'There is nothing on your Desktop to hide.',
)
})

it('fails with a clear message outside macOS', async () => {
setPlatform('linux')

await cli('hide')

expect(setHidden).not.toHaveBeenCalled()
expect(log).not.toHaveBeenCalled()
expect(error).toHaveBeenCalledWith(
expect.stringContaining('only works on macOS'),
)
expect(process.exitCode).toBe(1)
})

it('reports chflags errors instead of claiming success', async () => {
jest.mocked(setHidden).mockRejectedValue(
Object.assign(new Error('Command failed: chflags hidden ...'), {
stderr: 'chflags: /Users/test/Desktop/a.png: Operation not permitted\n',
}),
)

await cli('hide')

expect(log).not.toHaveBeenCalled()
expect(error).toHaveBeenCalledWith(
expect.stringContaining(
'chflags: /Users/test/Desktop/a.png: Operation not permitted',
),
)
expect(process.exitCode).toBe(1)
})

it('falls back to the error message when there is no stderr', async () => {
jest
.mocked(setHidden)
.mockRejectedValue(
new Error(
"ENOENT: no such file or directory, scandir '/Users/test/Desktop'",
),
)

await cli('unhide')

expect(error).toHaveBeenCalledWith(
expect.stringContaining('Could not unhide your Desktop items.'),
)
expect(error).toHaveBeenCalledWith(
expect.stringContaining('ENOENT: no such file or directory'),
)
expect(process.exitCode).toBe(1)
})
})
Loading
Loading