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
12 changes: 12 additions & 0 deletions src/cli/install-tool/base-install.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ export abstract class BaseInstallService {
*/
readonly parent?: string;

/**
* Some tools can only be installed as root, so they are only available at
* image build time. Eg. git is installed via apt.
*/
readonly needsRoot: boolean = false;

/**
* Tools which are not installed into a versioned tool path can't be
* uninstalled, eg. git is installed system wide via apt.
*/
readonly canUninstall: boolean = true;

/**
* Optional tool type for dynamic uninstallation support.
* Currently `npm`, `gem` or `pip`.
Expand Down
2 changes: 2 additions & 0 deletions src/cli/install-tool/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { ErlangInstallService } from '../tools/erlang/index.ts';
import { FlutterInstallService } from '../tools/flutter.ts';
import { FluxInstallService } from '../tools/flux.ts';
import { GhInstallService } from '../tools/gh.ts';
import { GitInstallService } from '../tools/git/index.ts';
import { GitLfsInstallService } from '../tools/git/lfs.ts';
import { GleamInstallService } from '../tools/gleam.ts';
import { GolangInstallService } from '../tools/golang.ts';
Expand Down Expand Up @@ -156,6 +157,7 @@ async function prepareInstallContainer(): Promise<Container> {
container.bind(INSTALL_TOOL_TOKEN).to(FlutterInstallService);
container.bind(INSTALL_TOOL_TOKEN).to(FluxInstallService);
container.bind(INSTALL_TOOL_TOKEN).to(GhInstallService);
container.bind(INSTALL_TOOL_TOKEN).to(GitInstallService);
container.bind(INSTALL_TOOL_TOKEN).to(GitLfsInstallService);
container.bind(INSTALL_TOOL_TOKEN).to(GhcInstallService);
container.bind(INSTALL_TOOL_TOKEN).to(GleamInstallService);
Expand Down
93 changes: 82 additions & 11 deletions src/cli/install-tool/install-tool.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from 'node:fs/promises';
import { execa } from 'execa';
import type { Container } from 'inversify';
import { type Container, injectFromHierarchy, injectable } from 'inversify';
import { beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
import { initializeTools, prepareTools } from '../prepare-tool/index.ts';
import {
Expand All @@ -10,8 +10,9 @@ import {
createContainer,
} from '../services/index.ts';
import { BunInstallService } from '../tools/bun.ts';
import { BlockingChild, NotSupported } from '../utils/codes.ts';
import { BlockingChild, NotRoot, NotSupported } from '../utils/codes.ts';
import { isDockerBuild, logger } from '../utils/index.ts';
import { BaseInstallService } from './base-install.service.ts';
import { V1ToolInstallService } from './install-legacy-tool.service.ts';
import {
INSTALL_TOOL_TOKEN,
Expand All @@ -29,11 +30,43 @@ vi.mock('../utils/index.ts', async (importActual) => ({
isDockerBuild: vi.fn(),
}));

@injectable()
@injectFromHierarchy()
abstract class TestInstallService extends BaseInstallService {
override install(_version: string): Promise<void> {
return Promise.resolve();
}

override link(_version: string): Promise<void> {
return Promise.resolve();
}
}

/** a tool which can only be installed at image build time, like `git` */
@injectable()
@injectFromHierarchy()
class RootOnlyInstallService extends TestInstallService {
override readonly name = 'root-only';

override readonly needsRoot = true;
}

/** a tool which is installed system wide, like `git` */
@injectable()
@injectFromHierarchy()
class NoUninstallInstallService extends TestInstallService {
override readonly name = 'no-uninstall';

override readonly canUninstall = false;
}

describe('cli/install-tool/install-tool.service', () => {
const parent = createContainer();
parent.bind(InstallToolService).toSelf();
parent.bind(V1ToolInstallService).toSelf();
parent.bind(INSTALL_TOOL_TOKEN).to(BunInstallService);
parent.bind(INSTALL_TOOL_TOKEN).to(RootOnlyInstallService);
parent.bind(INSTALL_TOOL_TOKEN).to(NoUninstallInstallService);

let child: Container;
let install: InstallToolService;
Expand All @@ -57,20 +90,32 @@ describe('cli/install-tool/install-tool.service', () => {
describe('install', () => {
test('writes version if tool is not installed', async () => {
const ver = await child.getAsync(VersionService);
const bun = await child.getAsync<BunInstallService>(INSTALL_TOOL_TOKEN);
vi.mocked(bun).needsInitialize.mockReturnValueOnce(true);
vi.mocked(bun).needsPrepare.mockReturnValueOnce(true);
vi.mocked(
BunInstallService.prototype,
).needsInitialize.mockReturnValueOnce(true);
vi.mocked(BunInstallService.prototype).needsPrepare.mockReturnValueOnce(
true,
);
expect(await install.install('bun', '1.0.0')).toBeUndefined();
expect(await ver.getCurrent('bun')).toMatchObject({
name: 'bun',
tool: { name: 'bun', version: '1.0.0' },
});
});

test('fails if the tool needs root', async () => {
expect(await install.install('root-only', '1.0.0')).toBe(NotRoot);
expect(logger.fatal).toHaveBeenCalledExactlyOnceWith(
{ tool: 'root-only' },
'tool must be installed as root',
);
});

test('writes version even if tool is installed', async () => {
const ver = await child.getAsync(VersionService);
const bun = await child.getAsync<BunInstallService>(INSTALL_TOOL_TOKEN);
vi.mocked(bun).isInstalled.mockResolvedValueOnce(true);
vi.mocked(BunInstallService.prototype).isInstalled.mockResolvedValueOnce(
true,
);
expect(await install.install('bun', '1.0.1')).toBeUndefined();
expect(await ver.getCurrent('bun')).toMatchObject({
name: 'bun',
Expand Down Expand Up @@ -160,16 +205,18 @@ describe('cli/install-tool/install-tool.service', () => {
});

test('aborts when the tool cannot be prepared', async () => {
const bun = await child.getAsync<BunInstallService>(INSTALL_TOOL_TOKEN);
vi.mocked(bun).needsPrepare.mockReturnValueOnce(true);
vi.mocked(BunInstallService.prototype).needsPrepare.mockReturnValueOnce(
true,
);
vi.mocked(prepareTools).mockResolvedValueOnce(1);

expect(await install.install('bun', '1.1.0')).toBe(1);
});

test('aborts when the tool cannot be initialized', async () => {
const bun = await child.getAsync<BunInstallService>(INSTALL_TOOL_TOKEN);
vi.mocked(bun).needsInitialize.mockReturnValueOnce(true);
vi.mocked(
BunInstallService.prototype,
).needsInitialize.mockReturnValueOnce(true);
vi.mocked(initializeTools).mockResolvedValueOnce(1);

expect(await install.install('bun', '1.1.1')).toBe(1);
Expand Down Expand Up @@ -216,6 +263,30 @@ describe('cli/install-tool/install-tool.service', () => {
);
});

test('fails if the tool cannot be uninstalled', async () => {
const ver = await child.getAsync(VersionService);
await ver.addInstalled({ name: 'no-uninstall', version: '1.0.0' });

expect(await install.uninstall('no-uninstall', '1.0.0')).toBe(
NotSupported,
);
expect(logger.fatal).toHaveBeenCalledExactlyOnceWith(
{ tool: 'no-uninstall' },
'tool cannot be uninstalled',
);
});

test('fails if the tool needs root', async () => {
const ver = await child.getAsync(VersionService);
await ver.addInstalled({ name: 'root-only', version: '1.0.0' });

expect(await install.uninstall('root-only', '1.0.0')).toBe(NotRoot);
expect(logger.fatal).toHaveBeenCalledExactlyOnceWith(
{ tool: 'root-only' },
'tool must be uninstalled as root',
);
});

test('dry run', async () => {
expect(await install.install('bun', '3.0.0')).toBeUndefined();

Expand Down
22 changes: 21 additions & 1 deletion src/cli/install-tool/install-tool.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@ import {
VersionService,
} from '../services/index.ts';
import type { ToolState } from '../services/version.service';
import { BlockingChild, MissingParent, NotSupported } from '../utils/codes.ts';
import {
BlockingChild,
MissingParent,
NotRoot,
NotSupported,
} from '../utils/codes.ts';
import {
cleanAptFiles,
cleanTmpFiles,
Expand Down Expand Up @@ -62,6 +67,11 @@ export class InstallToolService {
await this.ipc.start();
this._link.clear();
if (toolSvc) {
if (toolSvc.needsRoot && !this.envSvc.isRoot) {
logger.fatal({ tool }, 'tool must be installed as root');
return NotRoot;
}

let parent: ToolState | null = null;

if (toolSvc.parent) {
Expand Down Expand Up @@ -237,6 +247,16 @@ export class InstallToolService {

const toolSvc = this.toolSvcs.find((t) => t.name === tool);
if (toolSvc) {
if (!toolSvc.canUninstall) {
logger.fatal({ tool }, 'tool cannot be uninstalled');
return NotSupported;
}

if (toolSvc.needsRoot && !this.envSvc.isRoot) {
logger.fatal({ tool }, 'tool must be uninstalled as root');
return NotRoot;
}

logger.debug({ tool }, 'validate tool');
const childs = await this.versionSvc.getChilds({ name: tool, version });
if (childs.length) {
Expand Down
2 changes: 2 additions & 0 deletions src/cli/prepare-tool/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { PowershellPrepareService } from '../tools/dotnet/powershell.ts';
import { ElixirPrepareService } from '../tools/erlang/elixir.ts';
import { ErlangPrepareService } from '../tools/erlang/index.ts';
import { FlutterPrepareService } from '../tools/flutter.ts';
import { GitPrepareService } from '../tools/git/index.ts';
import { GolangPrepareService } from '../tools/golang.ts';
import { CabalPrepareService } from '../tools/haskell/cabal.ts';
import { GhcPrepareService } from '../tools/haskell/ghc.ts';
Expand Down Expand Up @@ -61,6 +62,7 @@ async function prepareContainer(): Promise<Container> {
container.bind(PREPARE_TOOL_TOKEN).to(ErlangPrepareService);
container.bind(PREPARE_TOOL_TOKEN).to(FlutterPrepareService);
container.bind(PREPARE_TOOL_TOKEN).to(GhcPrepareService);
container.bind(PREPARE_TOOL_TOKEN).to(GitPrepareService);
container.bind(PREPARE_TOOL_TOKEN).to(GolangPrepareService);
container.bind(PREPARE_TOOL_TOKEN).to(JavaPrepareService);
container.bind(PREPARE_TOOL_TOKEN).to(JavaJrePrepareService);
Expand Down
148 changes: 148 additions & 0 deletions src/cli/tools/git/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { readFile } from 'node:fs/promises';
import { codeBlock } from 'common-tags';
import { beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
import { getDistro } from '../../utils/index.ts';
import { GitInstallService, GitPrepareService } from './index.ts';
import { scope } from '~test/http-mock.ts';
import { ensurePaths, rootPath } from '~test/path.ts';
import { toolContext } from '~test/tool.ts';

const { execaMock } = vi.hoisted(() => ({ execaMock: vi.fn() }));
vi.mock('execa', () => ({ execa: execaMock }));
vi.mock('../../utils/index.ts', async (importActual) => ({
...(await importActual<typeof import('../../utils/index.ts')>()),
getDistro: vi.fn(),
}));

describe('cli/tools/git/index', () => {
beforeAll(async () => {
// `etc/apt/sources.list.d` ships with the image
await ensurePaths([
'tmp',
'etc/apt/sources.list.d',
'opt/containerbase/bin',
]);
});

beforeEach(() => {
vi.mocked(getDistro).mockResolvedValue({
name: 'Ubuntu',
versionCode: 'noble',
versionId: '24.04',
});
// CI configures an apt proxy, which `AptService` would write to `/etc`
vi.stubEnv('APT_HTTP_PROXY', undefined);
execaMock.mockResolvedValue({
failed: false,
stdout: 'git version 2.55.0',
});
});

describe('GitPrepareService', () => {
test('adds the ppa', async () => {
const { svc } = await toolContext(GitPrepareService);
scope('http://keyserver.ubuntu.com')
.get('/pks/lookup')
.query(true)
.reply(200, 'public key');

await expect(svc.prepare()).resolves.toBeUndefined();

expect(await readFile(rootPath('etc/apt/keyrings/git.asc'), 'utf8')).toBe(
'public key',
);
expect(
await readFile(rootPath('etc/apt/sources.list.d/git.sources'), 'utf8'),
).toBe(codeBlock`
Types: deb
URIs: https://ppa.launchpadcontent.net/git-core/ppa/ubuntu
Suites: noble
Components: main
Architectures: amd64
Signed-By: /etc/apt/keyrings/git.asc
`);
});
});

describe('GitInstallService', () => {
test('install', async () => {
const { svc } = await toolContext(GitInstallService);

await expect(svc.install('2.55.0')).resolves.toBeUndefined();

expect(execaMock).toHaveBeenCalledWith('apt-get', [
'-qq',
'install',
'-y',
'git',
]);
});

test('install: coerces a vendor version suffix', async () => {
const { svc } = await toolContext(GitInstallService);
execaMock.mockResolvedValue({
failed: false,
stdout: 'git version 2.55.0-1ubuntu1',
});

await expect(svc.install('2.55.0')).resolves.toBeUndefined();
});

test('install: throws on an unparsable version', async () => {
const { svc } = await toolContext(GitInstallService);
execaMock.mockResolvedValue({ failed: false, stdout: 'git version foo' });

await expect(svc.install('2.55.0')).rejects.toThrow(
'Could not parse the git version: git version foo',
);
});

test('install: rejects a version below the minimum', async () => {
const { svc } = await toolContext(GitInstallService);
execaMock.mockResolvedValue({
failed: false,
stdout: 'git version 2.32.0',
});

await expect(svc.install('2.32.0')).rejects.toThrow(
'Git version mismatch! Expected: 2.33.0, got: 2.32.0',
);
});

test('link does nothing', async () => {
const { svc } = await toolContext(GitInstallService);

await expect(svc.link('2.55.0')).resolves.toBeUndefined();
});

test('allows all safe directories', async () => {
const { svc } = await toolContext(GitInstallService);

await expect(svc.postInstall('2.55.0')).resolves.toBeUndefined();

expect(execaMock).toHaveBeenCalledWith(
'git',
['config', '--system', 'safe.directory', '*'],
expect.objectContaining({ stdio: ['inherit', 'inherit', 1] }),
);
});

test('prints the version', async () => {
const { svc } = await toolContext(GitInstallService);

await expect(svc.test('2.55.0')).resolves.toBeUndefined();

expect(execaMock).toHaveBeenCalledWith(
'git',
['--version'],
expect.objectContaining({ stdio: ['inherit', 'inherit', 1] }),
);
});

test('cannot be uninstalled', async () => {
const { svc } = await toolContext(GitInstallService);

expect(svc.canUninstall).toBe(false);
});
});
});
Loading