diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 0000000..4b1f876 --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,17 @@ +name: Build + +on: + push: + branches: + - "2" + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: oven-sh/setup-bun@v1 + with: + bun-version: latest + - run: bun test + - run: bun bin diff --git a/.gitignore b/.gitignore index 417d081..2fc1737 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ node_modules /autorestic +test diff --git a/src/lock/index.test.ts b/src/lock/index.test.ts index 0884e54..6c50300 100644 --- a/src/lock/index.test.ts +++ b/src/lock/index.test.ts @@ -1,7 +1,7 @@ -import { describe, expect, mock, test, beforeEach } from 'bun:test' -import { lockRepo } from '.' -import { Context } from '../models/context' +import { beforeEach, describe, expect, test } from 'bun:test' import { mkdir, rm } from 'node:fs/promises' +import { lockRepo, unlockRepo, waitForRepo } from '.' +import { Context } from '../models/context' const mockPath = './test/' const mockContext: Context = { config: { meta: { path: mockPath } } } as any @@ -13,8 +13,39 @@ describe('lock', () => { await mkdir(mockPath, { recursive: true }) }) - test('lock', () => { - lockRepo(mockContext, 'foo') - // lockRepo(mockContext, 'foo') + test('simple lock and unlock', () => { + const repo = 'foo' + lockRepo(mockContext, repo) + unlockRepo(mockContext, repo) + }) + + test('should not be able to lock twice', () => { + const repo = 'foo' + lockRepo(mockContext, repo) + expect(() => { + lockRepo(mockContext, repo) + }).toThrow() + unlockRepo(mockContext, repo) + lockRepo(mockContext, repo) + }) + + test('should be able to eventually acquire lock', async () => { + const repo = 'foo' + lockRepo(mockContext, repo) + setTimeout(() => unlockRepo(mockContext, repo), 50) + await waitForRepo(mockContext, repo, 1) + }) + + test('unlock', () => { + unlockRepo(mockContext, 'foo') + }) + + test('multiple', () => { + const a = 'foo' + const b = 'bar' + lockRepo(mockContext, a) + lockRepo(mockContext, b) + unlockRepo(mockContext, b) + unlockRepo(mockContext, a) }) }) diff --git a/src/lock/index.ts b/src/lock/index.ts index 42da55d..9876fc0 100644 --- a/src/lock/index.ts +++ b/src/lock/index.ts @@ -51,11 +51,11 @@ export function lockRepo(ctx: Context, repo: string) { */ export async function waitForRepo(ctx: Context, repo: string, timeout = 10) { const now = Date.now() - while (Date.now() - now < timeout * 1_000) { + while (Date.now() - now <= timeout * 1_000) { try { lockRepo(ctx, repo) l.trace('repo is free again', { repo }) - break + return } catch { l.trace('waiting for repo to be unlocked', { repo }) await wait(0.1) // Wait for 100ms