feat: implement base template support
This commit is contained in:
34
internal/template/base_templates.go
Normal file
34
internal/template/base_templates.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package template
|
||||
|
||||
type baseTemplate struct {
|
||||
Name string `json:"name"`
|
||||
ID string `json:"id"`
|
||||
Content string `json:"-"`
|
||||
}
|
||||
|
||||
var baseTemplates = []baseTemplate{fedora40WithSSH}
|
||||
|
||||
var baseTemplateMap = map[string]baseTemplate{
|
||||
"empty": {
|
||||
Name: "Empty",
|
||||
ID: "empty",
|
||||
Content: "",
|
||||
},
|
||||
"fedora-40-openssh": fedora40WithSSH,
|
||||
}
|
||||
|
||||
var fedora40WithSSH = baseTemplate{
|
||||
Name: "Fedora 40 With OpenSSH Server",
|
||||
ID: "fedora-40-openssh",
|
||||
Content: `FROM fedora:40
|
||||
|
||||
RUN dnf install -y openssh-server \
|
||||
&& mkdir -p /etc/ssh \
|
||||
&& ssh-keygen -q -N "" -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key \
|
||||
&& useradd testuser \
|
||||
&& echo "testuser:12345678" | chpasswd
|
||||
&& usermod -aG wheel testuser
|
||||
|
||||
CMD ["/usr/sbin/sshd", "-D"]
|
||||
`,
|
||||
}
|
@@ -14,6 +14,7 @@ type createTemplateRequestBody struct {
|
||||
Description string `json:"description"`
|
||||
Content string `json:"content"`
|
||||
Documentation string `json:"documentation"`
|
||||
BaseTemplate string `json:"baseTemplate"`
|
||||
}
|
||||
|
||||
type postTemplateRequestBody struct {
|
||||
@@ -33,6 +34,15 @@ func fetchAllTemplates(c echo.Context) error {
|
||||
return c.JSON(http.StatusOK, templates)
|
||||
}
|
||||
|
||||
func fetchBaseTemplates(c echo.Context) error {
|
||||
mgr := templateManagerFrom(c)
|
||||
templates, err := mgr.findBaseTemplates(c.Request().Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.JSON(http.StatusOK, templates)
|
||||
}
|
||||
|
||||
func fetchTemplate(c echo.Context) error {
|
||||
mgr := templateManagerFrom(c)
|
||||
template, err := mgr.findTemplate(c.Request().Context(), c.Param("templateName"))
|
||||
@@ -79,8 +89,9 @@ func createTemplate(c echo.Context) error {
|
||||
}
|
||||
|
||||
createdTemplate, err := mgr.createTemplate(c.Request().Context(), createTemplateOptions{
|
||||
name: name,
|
||||
description: body.Description,
|
||||
name: name,
|
||||
description: body.Description,
|
||||
baseTemplate: body.BaseTemplate,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
@@ -14,4 +14,5 @@ func DefineRoutes(g *echo.Group, services service.Services) {
|
||||
g.GET("/templates/:templateName/:filePath", fetchTemplateFile, validateTemplateName, validateTemplateFilePath)
|
||||
g.POST("/templates/:templateName/:filePath", updateTemplateFile, validateTemplateName, validateTemplateFilePath)
|
||||
g.GET("/template-images", fetchAllTemplateImages)
|
||||
g.GET("/base-templates", fetchBaseTemplates)
|
||||
}
|
||||
|
@@ -22,8 +22,9 @@ type templateManager struct {
|
||||
}
|
||||
|
||||
type createTemplateOptions struct {
|
||||
name string
|
||||
description string
|
||||
baseTemplate string
|
||||
name string
|
||||
description string
|
||||
}
|
||||
|
||||
type updateTemplateOptions struct {
|
||||
@@ -38,6 +39,7 @@ type buildTemplateOptions struct {
|
||||
}
|
||||
|
||||
var errTemplateNotFound = errors.New("template not found")
|
||||
var errBaseTemplateNotFound = errors.New("base template not found")
|
||||
var errTemplateFileNotFound = errors.New("template file not found")
|
||||
|
||||
func (mgr *templateManager) beginTx(ctx context.Context) (bun.Tx, error) {
|
||||
@@ -48,6 +50,10 @@ func (mgr *templateManager) beginTx(ctx context.Context) (bun.Tx, error) {
|
||||
return tx, nil
|
||||
}
|
||||
|
||||
func (mgr *templateManager) findBaseTemplates(ctx context.Context) ([]baseTemplate, error) {
|
||||
return baseTemplates, nil
|
||||
}
|
||||
|
||||
func (mgr *templateManager) findAllTemplates(ctx context.Context) ([]template, error) {
|
||||
var templates []template
|
||||
err := mgr.db.NewSelect().Model(&templates).Scan(ctx)
|
||||
@@ -69,7 +75,7 @@ func (mgr *templateManager) findTemplate(ctx context.Context, name string) (*tem
|
||||
var template template
|
||||
err := mgr.db.NewSelect().Model(&template).
|
||||
Relation("Files").
|
||||
Where("name = ?", name).
|
||||
Where("Name = ?", name).
|
||||
Scan(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
@@ -91,7 +97,7 @@ func (mgr *templateManager) findTemplate(ctx context.Context, name string) (*tem
|
||||
func (mgr *templateManager) hasTemplate(ctx context.Context, name string) (bool, error) {
|
||||
exists, err := mgr.db.NewSelect().
|
||||
Table("templates").
|
||||
Where("name = ?", name).
|
||||
Where("Name = ?", name).
|
||||
Exists(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
@@ -115,6 +121,11 @@ func (mgr *templateManager) createTemplate(ctx context.Context, opts createTempl
|
||||
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
|
||||
baseTemplate, ok := baseTemplateMap[opts.baseTemplate]
|
||||
if !ok {
|
||||
return nil, errBaseTemplateNotFound
|
||||
}
|
||||
|
||||
t := template{
|
||||
ID: id,
|
||||
Name: opts.name,
|
||||
@@ -126,7 +137,7 @@ func (mgr *templateManager) createTemplate(ctx context.Context, opts createTempl
|
||||
dockerfile := templateFile{
|
||||
TemplateID: id,
|
||||
FilePath: "Dockerfile",
|
||||
Content: make([]byte, 0),
|
||||
Content: []byte(baseTemplate.Content),
|
||||
}
|
||||
readme := templateFile{
|
||||
TemplateID: id,
|
||||
@@ -167,7 +178,7 @@ func (mgr *templateManager) updateTemplate(ctx context.Context, name string, opt
|
||||
|
||||
var template template
|
||||
err := tx.NewUpdate().Model(&template).
|
||||
Where("name = ?", name).
|
||||
Where("Name = ?", name).
|
||||
Set("description = ?", opts.description).
|
||||
Returning("*").
|
||||
Scan(ctx)
|
||||
@@ -320,7 +331,7 @@ func (mgr *templateManager) deleteTemplate(ctx context.Context, name string) err
|
||||
}
|
||||
|
||||
res, err := tx.NewDelete().Table("templates").
|
||||
Where("name = ?", name).
|
||||
Where("Name = ?", name).
|
||||
Exec(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
@@ -353,7 +364,7 @@ func (mgr *templateManager) findTemplateFile(ctx context.Context, templateName,
|
||||
var tmpl template
|
||||
err := mgr.db.NewSelect().Model(&tmpl).
|
||||
Column("id").
|
||||
Where("name = ?", templateName).
|
||||
Where("Name = ?", templateName).
|
||||
Scan(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
@@ -386,7 +397,7 @@ func (mgr *templateManager) updateTemplateFile(ctx context.Context, templateName
|
||||
var template template
|
||||
err = tx.NewSelect().Model(&template).
|
||||
Column("id").
|
||||
Where("name = ?", templateName).
|
||||
Where("Name = ?", templateName).
|
||||
Scan(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
|
@@ -1,6 +1,11 @@
|
||||
import { useCallback, useState } from "react";
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import type { Template, TemplateMeta, TemplateImage } from "./types";
|
||||
import type {
|
||||
Template,
|
||||
TemplateMeta,
|
||||
TemplateImage,
|
||||
BaseTemplate,
|
||||
} from "./types";
|
||||
import { fetchApi } from "@/api";
|
||||
|
||||
function useTemplates() {
|
||||
@@ -47,11 +52,16 @@ function useCreateTemplate() {
|
||||
async ({
|
||||
name,
|
||||
description,
|
||||
}: { name: string; description: string }): Promise<Template | null> => {
|
||||
baseTemplate,
|
||||
}: {
|
||||
name: string;
|
||||
description: string;
|
||||
baseTemplate: string;
|
||||
}): Promise<Template | null> => {
|
||||
try {
|
||||
const res = await fetchApi(`/templates/${name}`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ description }),
|
||||
body: JSON.stringify({ description, baseTemplate }),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
@@ -150,6 +160,14 @@ function useTemplateImages() {
|
||||
);
|
||||
}
|
||||
|
||||
function useBaseTemplates() {
|
||||
return useSWR(
|
||||
"/base-templates",
|
||||
(): Promise<BaseTemplate[]> =>
|
||||
fetchApi("/base-templates").then((res) => res.json()),
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
useTemplates,
|
||||
useTemplate,
|
||||
@@ -159,4 +177,5 @@ export {
|
||||
buildTemplate,
|
||||
useDeleteTemplate,
|
||||
useTemplateImages,
|
||||
useBaseTemplates,
|
||||
};
|
||||
|
@@ -1,51 +1,26 @@
|
||||
import { PageHeader } from "@/components/ui/page-header.tsx";
|
||||
import { MainSidebar } from "@/components/main-sidebar.tsx";
|
||||
import { Button } from "@/components/ui/button.tsx";
|
||||
import { Info, Loader2, Pencil, Plus, Trash2 } from "lucide-react";
|
||||
import { Dialog, DialogTrigger } from "@/components/ui/dialog";
|
||||
import { PageHeader } from "@/components/ui/page-header.tsx";
|
||||
import { Page } from "@/components/ui/page.tsx";
|
||||
import { SidebarProvider } from "@/components/ui/sidebar.tsx";
|
||||
import { MainSidebar } from "@/components/main-sidebar.tsx";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
TableHead,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import {
|
||||
Dialog,
|
||||
DialogTrigger,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Link, useRouter } from "@tanstack/react-router";
|
||||
import { object, pattern, string, type Infer } from "superstruct";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { superstructResolver } from "@hookform/resolvers/superstruct";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { useCreateTemplate, useDeleteTemplate, useTemplates } from "./api";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import dayjs from "dayjs";
|
||||
import { ToastAction } from "@radix-ui/react-toast";
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
|
||||
const NewTemplateForm = object({
|
||||
templateName: pattern(string(), /^[\w-]+$/),
|
||||
templateDescription: string(),
|
||||
});
|
||||
import { useToast } from "@/hooks/use-toast";
|
||||
import { ToastAction } from "@radix-ui/react-toast";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import dayjs from "dayjs";
|
||||
import { Info, Pencil, Plus, Trash2 } from "lucide-react";
|
||||
import { useDeleteTemplate, useTemplates } from "./api";
|
||||
import { NewTemplateDialog } from "./new-template-dialog";
|
||||
|
||||
function TemplatesDashboard() {
|
||||
return (
|
||||
@@ -172,83 +147,4 @@ function TemplateTable() {
|
||||
);
|
||||
}
|
||||
|
||||
function NewTemplateDialog() {
|
||||
const router = useRouter();
|
||||
const { createTemplate, isCreatingTemplate } = useCreateTemplate();
|
||||
|
||||
const form = useForm({
|
||||
resolver: superstructResolver(NewTemplateForm),
|
||||
disabled: isCreatingTemplate,
|
||||
defaultValues: {
|
||||
templateName: "",
|
||||
templateDescription: "",
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(values: Infer<typeof NewTemplateForm>) {
|
||||
const createdTemplate = await createTemplate({
|
||||
name: values.templateName,
|
||||
description: values.templateDescription,
|
||||
});
|
||||
if (createdTemplate) {
|
||||
router.navigate({ to: `/templates/${createdTemplate.name}` });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>New template</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new template for workspaces
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="templateName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Template name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="my-template" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Must only contain alphanumeric characters and "-".
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="templateDescription"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Optional description for this template
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<DialogFooter>
|
||||
<Button disabled={isCreatingTemplate} type="submit">
|
||||
{isCreatingTemplate ? <Loader2 className="animate-spin" /> : null}
|
||||
Create
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
);
|
||||
}
|
||||
|
||||
export { TemplatesDashboard };
|
||||
|
168
web/src/templates/new-template-dialog.tsx
Normal file
168
web/src/templates/new-template-dialog.tsx
Normal file
@@ -0,0 +1,168 @@
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DialogHeader, DialogFooter } from "@/components/ui/dialog";
|
||||
import {
|
||||
Form,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { superstructResolver } from "@hookform/resolvers/superstruct";
|
||||
import {
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from "@/components/ui/dialog";
|
||||
import { useRouter } from "@tanstack/react-router";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { nonempty, object, pattern, string, type Infer } from "superstruct";
|
||||
import { useBaseTemplates, useCreateTemplate } from "./api";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
|
||||
const NewTemplateForm = object({
|
||||
baseTemplate: nonempty(string()),
|
||||
templateName: pattern(string(), /^[\w-]+$/),
|
||||
templateDescription: string(),
|
||||
});
|
||||
|
||||
function NewTemplateDialog() {
|
||||
return (
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>New template</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new template for workspaces
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<TemplateForm />
|
||||
</DialogContent>
|
||||
);
|
||||
}
|
||||
|
||||
function TemplateForm() {
|
||||
const router = useRouter();
|
||||
const { createTemplate, isCreatingTemplate } = useCreateTemplate();
|
||||
const form = useForm({
|
||||
resolver: superstructResolver(NewTemplateForm),
|
||||
disabled: isCreatingTemplate,
|
||||
defaultValues: {
|
||||
baseTemplate: "empty",
|
||||
templateName: "",
|
||||
templateDescription: "",
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(values: Infer<typeof NewTemplateForm>) {
|
||||
const createdTemplate = await createTemplate({
|
||||
name: values.templateName,
|
||||
description: values.templateDescription,
|
||||
baseTemplate: values.baseTemplate,
|
||||
});
|
||||
if (createdTemplate) {
|
||||
router.navigate({ to: `/templates/${createdTemplate.name}` });
|
||||
}
|
||||
}
|
||||
|
||||
const { data: baseTemplates, isLoading, error } = useBaseTemplates();
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="w-full flex items-center justify-center">
|
||||
<LoadingSpinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !baseTemplates) {
|
||||
return (
|
||||
<p className="opacity-80">
|
||||
An error occurred when fetching available options.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="baseTemplate"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Base template</FormLabel>
|
||||
<Select onValueChange={field.onChange} defaultValue={field.value}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a base template" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="empty">Empty</SelectItem>
|
||||
{baseTemplates.map((template) => (
|
||||
<SelectItem key={template.id} value={template.id}>
|
||||
{template.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="templateName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Template name</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="my-template" {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Must only contain alphanumeric characters and "-".
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="templateDescription"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Description</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} />
|
||||
</FormControl>
|
||||
<FormDescription>
|
||||
Optional description for this template
|
||||
</FormDescription>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<DialogFooter>
|
||||
<Button disabled={isCreatingTemplate} type="submit">
|
||||
{isCreatingTemplate ? <Loader2 className="animate-spin" /> : null}
|
||||
Create
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
}
|
||||
|
||||
export { NewTemplateDialog };
|
@@ -19,4 +19,15 @@ interface FileInTemplate {
|
||||
content: string;
|
||||
}
|
||||
|
||||
export type { TemplateMeta, Template, FileInTemplate, TemplateImage };
|
||||
interface BaseTemplate {
|
||||
name: string;
|
||||
id: string;
|
||||
}
|
||||
|
||||
export type {
|
||||
TemplateMeta,
|
||||
Template,
|
||||
FileInTemplate,
|
||||
TemplateImage,
|
||||
BaseTemplate,
|
||||
};
|
||||
|
Reference in New Issue
Block a user