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
6 changes: 6 additions & 0 deletions .changeset/get-template-tags.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'e2b': patch
'@e2b/python-sdk': patch
---

Add `getTags`/`get_tags` method to list all tags for a template
31 changes: 30 additions & 1 deletion packages/js-sdk/src/template/buildApi.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ApiClient, handleApiError, paths } from '../api'
import { ApiClient, handleApiError, paths, components } from '../api'
import { stripAnsi } from '../utils'
import { BuildError, FileUploadError, TemplateError } from '../errors'
import { LogEntry } from './logger'
Expand All @@ -7,6 +7,7 @@ import {
BuildStatusReason,
TemplateBuildStatus,
TemplateBuildStatusResponse,
TemplateTag,
TemplateTagInfo,
} from './types'

Expand Down Expand Up @@ -358,3 +359,31 @@ export async function removeTags(
throw error
}
}

export async function getTemplateTags(
client: ApiClient,
{ templateID }: { templateID: string }
): Promise<TemplateTag[]> {
const res = await client.api.GET('/templates/{templateID}/tags', {
params: {
path: {
templateID,
},
},
})

const error = handleApiError(res, TemplateError)
if (error) {
throw error
}

if (!res.data) {
throw new TemplateError('Failed to get template tags')
}

return res.data.map((item: components['schemas']['TemplateTag']) => ({
tag: item.tag,
buildId: item.buildID,
createdAt: new Date(item.createdAt),
}))
}
28 changes: 28 additions & 0 deletions packages/js-sdk/src/template/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { runtime } from '../utils'
import {
assignTags,
checkAliasExists,
getTemplateTags,
removeTags,
getBuildStatus,
getFileUploadLink,
Expand Down Expand Up @@ -34,6 +35,7 @@ import {
TemplateFinal,
TemplateFromImage,
TemplateOptions,
TemplateTag,
TemplateTagInfo,
} from './types'
import {
Expand Down Expand Up @@ -371,6 +373,30 @@ export class TemplateBase
return removeTags(client, { name, tags: normalizedTags })
}

/**
* Get all tags for a template.
*
* @param templateId Template ID or name
* @param options Authentication options
* @returns Array of tag details including tag name, buildId, and creation date
*
* @example
* ```ts
* const tags = await Template.getTags('my-template')
* for (const tag of tags) {
* console.log(`Tag: ${tag.tag}, Build: ${tag.buildId}, Created: ${tag.createdAt}`)
* }
* ```
*/
static async getTags(
templateId: string,
options?: ConnectionOpts
): Promise<TemplateTag[]> {
const config = new ConnectionConfig(options)
const client = new ApiClient(config)
return getTemplateTags(client, { templateID: templateId })
}

fromDebianImage(variant: string = 'stable'): TemplateBuilder {
return this.fromImage(`debian:${variant}`)
}
Expand Down Expand Up @@ -1265,6 +1291,7 @@ Template.exists = TemplateBase.exists
Template.aliasExists = TemplateBase.aliasExists
Template.assignTags = TemplateBase.assignTags
Template.removeTags = TemplateBase.removeTags
Template.getTags = TemplateBase.getTags
Template.toJSON = TemplateBase.toJSON
Template.toDockerfile = TemplateBase.toDockerfile

Expand All @@ -1279,5 +1306,6 @@ export type {
TemplateBuildStatus,
TemplateBuildStatusResponse,
TemplateClass,
TemplateTag,
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you need to export this from index.ts as well

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In index.ts there is
94: export * from './template'

Which probably takes care of this? Everything works for me when testing it.

import pkg from './packages/js-sdk/dist/index.js'
const { Template, TemplateTag } = pkg

console.log('TemplateTag:', TemplateTag)

const tags = await Template.getTags('w8h2fkcozzr3bz100iyl')
console.log(`Found ${tags.length} tags:`)
for (const tag of tags) {
  console.log(`  Tag: ${tag.tag}, Build: ${tag.buildId}, Created: ${tag.createdAt}`)
}

TemplateTagInfo,
} from './types'
18 changes: 18 additions & 0 deletions packages/js-sdk/src/template/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,24 @@ export type TemplateTagInfo = {
tags: string[]
}

/**
* Detailed information about a single template tag.
*/
export type TemplateTag = {
/**
* Name of the tag.
*/
tag: string
/**
* Build identifier associated with this tag.
*/
buildId: string
/**
* When this tag was assigned.
*/
createdAt: Date
}

/**
* Types of instructions that can be used in a template.
*/
Expand Down
39 changes: 39 additions & 0 deletions packages/js-sdk/tests/template/tags.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,28 @@ const mockHandlers = [
tags: tags,
})
}),
// Get template tags endpoint
http.get(apiUrl('/templates/:templateID/tags'), ({ params }) => {
const { templateID } = params
if (templateID === 'nonexistent') {
return HttpResponse.json(
{ message: 'Template not found' },
{ status: 404 }
)
}
return HttpResponse.json([
{
tag: 'v1.0',
buildID: '00000000-0000-0000-0000-000000000000',
createdAt: '2024-01-15T10:30:00Z',
},
{
tag: 'latest',
buildID: '11111111-1111-1111-1111-111111111111',
createdAt: '2024-01-16T12:00:00Z',
},
])
}),
// Bulk delete endpoint
http.delete(apiUrl('/templates/tags'), async ({ request }) => {
const { name } = (await request.clone().json()) as {
Expand Down Expand Up @@ -81,6 +103,23 @@ describe('Template tags unit tests', () => {
).rejects.toThrow()
})
})

describe('Template.getTags', () => {
test('returns tags for a template', async () => {
const tags = await Template.getTags('my-template-id')
expect(tags).toHaveLength(2)
expect(tags[0].tag).toBe('v1.0')
expect(tags[0].buildId).toBe('00000000-0000-0000-0000-000000000000')
expect(tags[0].createdAt).toBeInstanceOf(Date)
expect(tags[1].tag).toBe('latest')
expect(tags[1].buildId).toBe('11111111-1111-1111-1111-111111111111')
expect(tags[1].createdAt).toBeInstanceOf(Date)
})

test('handles 404 for nonexistent template', async () => {
await expect(Template.getTags('nonexistent')).rejects.toThrow()
})
})
})

// Integration tests
Expand Down
2 changes: 2 additions & 0 deletions packages/python-sdk/e2b/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
CopyItem,
TemplateBuildStatus,
TemplateBuildStatusResponse,
TemplateTag,
TemplateTagInfo,
)
from .template_async.main import AsyncTemplate
Expand Down Expand Up @@ -179,6 +180,7 @@
"BuildStatusReason",
"TemplateBuildStatus",
"TemplateBuildStatusResponse",
"TemplateTag",
"TemplateTagInfo",
"ReadyCmd",
"wait_for_file",
Expand Down
17 changes: 17 additions & 0 deletions packages/python-sdk/e2b/template/types.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import List, Literal, Optional, TypedDict, Union
Expand Down Expand Up @@ -73,6 +74,22 @@ class TemplateTagInfo:
"""Assigned tags of the template."""


@dataclass
class TemplateTag:
"""
Detailed information about a single template tag.
"""

tag: str
"""Name of the tag."""

build_id: str
"""Build identifier associated with this tag."""

created_at: datetime
"""When this tag was assigned."""
Comment thread
mishushakov marked this conversation as resolved.


class InstructionType(str, Enum):
"""
Types of instructions that can be used in a template.
Expand Down
36 changes: 36 additions & 0 deletions packages/python-sdk/e2b/template_async/build_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from e2b.api.client.api.tags import (
post_templates_tags,
delete_templates_tags,
get_templates_template_id_tags,
)
from e2b.api.client.client import AuthenticatedClient
from e2b.api.client.models import (
Expand All @@ -33,6 +34,7 @@
BuildStatusReason,
TemplateBuildStatus,
TemplateBuildStatusResponse,
TemplateTag,
TemplateTagInfo,
)
from e2b.template.utils import get_build_step_index, tar_file_stream
Expand Down Expand Up @@ -336,3 +338,37 @@ async def remove_tags(client: AuthenticatedClient, name: str, tags: List[str]) -

if res.status_code >= 300:
raise handle_api_exception(res, TemplateException)


async def get_template_tags(
client: AuthenticatedClient, template_id: str
) -> List[TemplateTag]:
"""
Get all tags for a template.

Args:
client: Authenticated API client
template_id: Template ID or name
"""
res = await get_templates_template_id_tags.asyncio_detailed(
template_id=template_id,
client=client,
)

if res.status_code >= 300:
raise handle_api_exception(res, TemplateException)

if isinstance(res.parsed, Error):
raise TemplateException(f"API error: {res.parsed.message}")

if res.parsed is None:
raise TemplateException("Failed to get template tags")

return [
TemplateTag(
tag=item.tag,
build_id=str(item.build_id),
created_at=item.created_at,
)
for item in res.parsed
]
Comment thread
mishushakov marked this conversation as resolved.
32 changes: 31 additions & 1 deletion packages/python-sdk/e2b/template_async/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,13 @@
from e2b.template.consts import RESOLVE_SYMLINKS
from e2b.template.logger import LogEntry, LogEntryEnd, LogEntryStart
from e2b.template.main import TemplateBase, TemplateClass
from e2b.template.types import BuildInfo, InstructionType, TemplateTagInfo
from e2b.template.types import BuildInfo, InstructionType, TemplateTag, TemplateTagInfo
from e2b.template.utils import normalize_build_arguments, read_dockerignore

from .build_api import (
assign_tags,
check_alias_exists,
get_template_tags,
remove_tags,
get_build_status,
get_file_upload_link,
Expand Down Expand Up @@ -496,3 +497,32 @@ async def remove_tags(

normalized_tags = [tags] if isinstance(tags, str) else tags
await remove_tags(api_client, name, normalized_tags)

@staticmethod
async def get_tags(
template_id: str,
**opts: Unpack[ApiParams],
) -> List[TemplateTag]:
"""
Get all tags for a template.

:param template_id: Template ID or name
:return: List of TemplateTag with tag name, build_id, and created_at

Example
```python
from e2b import AsyncTemplate

tags = await AsyncTemplate.get_tags('my-template')
for tag in tags:
print(f"Tag: {tag.tag}, Build: {tag.build_id}, Created: {tag.created_at}")
```
"""
config = ConnectionConfig(**opts)
api_client = get_api_client(
config,
require_api_key=True,
require_access_token=False,
)

return await get_template_tags(api_client, template_id)
36 changes: 36 additions & 0 deletions packages/python-sdk/e2b/template_sync/build_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from e2b.api.client.api.tags import (
post_templates_tags,
delete_templates_tags,
get_templates_template_id_tags,
)
from e2b.api.client.client import AuthenticatedClient
from e2b.api.client.models import (
Expand All @@ -33,6 +34,7 @@
BuildStatusReason,
TemplateBuildStatus,
TemplateBuildStatusResponse,
TemplateTag,
TemplateTagInfo,
)
from e2b.template.utils import get_build_step_index, tar_file_stream
Expand Down Expand Up @@ -333,3 +335,37 @@ def remove_tags(client: AuthenticatedClient, name: str, tags: List[str]) -> None

if res.status_code >= 300:
raise handle_api_exception(res, TemplateException)


def get_template_tags(
client: AuthenticatedClient, template_id: str
) -> List[TemplateTag]:
"""
Get all tags for a template.

Args:
client: Authenticated API client
template_id: Template ID or name
"""
res = get_templates_template_id_tags.sync_detailed(
template_id=template_id,
client=client,
)

if res.status_code >= 300:
raise handle_api_exception(res, TemplateException)

if isinstance(res.parsed, Error):
raise TemplateException(f"API error: {res.parsed.message}")

if res.parsed is None:
raise TemplateException("Failed to get template tags")

return [
TemplateTag(
tag=item.tag,
build_id=str(item.build_id),
created_at=item.created_at,
)
for item in res.parsed
]
Loading