All files / features / pipelines PipelineFormPage.tsx

21.42% Statements 45/210
17.17% Branches 34/198
15.09% Functions 8/53
33.58% Lines 44/131

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308                    99x 1x 99x 99x         99x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                                                                                                             4x                                                                                                                                                                                                                                                                                                                                                                                                                                
import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Loader2 } from 'lucide-react'
import { useProject } from '@/features/projects/projectsApi'
import { useRepositories } from '@/features/repositories/repositoriesApi'
import { useCreatePipeline, useUpdatePipeline, usePipeline, useDeletePipeline } from './pipelinesApi'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Breadcrumb } from '@/shared/components/Breadcrumb'
import { ConfirmDialog } from '@/shared/components/ConfirmDialog'
 
const forbiddenBranches = ['main', 'master', 'default']
const gitBranchPattern = /^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,254}$/
 
export function PipelineFormPage() {
  const { projectId: urlProjectId, id } = useParams<{ projectId: string; id: string }>()
  const navigate = useNavigate()
  const isEdit = !!id
  const { data: pipeline } = usePipeline(id ?? '')
  const projId = urlProjectId ?? pipeline?.project_id ?? ''
  const { data: projectData } = useProject(projId)
  const project = projectData?.project
  const { data: reposData } = useRepositories()
  const repos = reposData?.data ?? []
  const createPipeline = useCreatePipeline(projId)
  const updatePipeline = useUpdatePipeline(id ?? '')
  const deletePipeline = useDeletePipeline()
 
  const [name, setName] = useState('')
  const [outputBranch, setOutputBranch] = useState('')
  const [enabled, setEnabled] = useState(true)
  const [description, setDescription] = useState('')
  const [repoId, setRepoId] = useState('')
  const [codePath, setCodePath] = useState('')
  const [manifestRepoId, setManifestRepoId] = useState('')
  const [manifestPath, setManifestPath] = useState('')
  const [showDelete, setShowDelete] = useState(false)
  const [outputBranchError, setOutputBranchError] = useState<string | null>(null)
 
  useEffect(() => {
    if (pipeline) {
      setName(pipeline.name)
      setOutputBranch(pipeline.output_branch ?? '')
      setEnabled(pipeline.enabled)
  I    setDescription(pipeline.description ?? '')
      setRepoId('')
      setCodePath('')
      const hashIdx = pipeline.manifest_source_url.indexOf('#')
      if (hashIdx !== -1) {
        const url = pipeline.manifest_source_url.slice(0, hashIdx)
        const path = pipeline.manifest_source_url.slice(hashIdx + 1)
        const matchedRepo = repos.find((r) => r.url === url)
        setManifestRepoId(matchedRepo?.id ?? '')
        setManifestPath(path)
      } else {
        setManifestRepoId('')
        setManifestPath('')
      }
    }
  }, [pipeline, repos])

  function validateOutputBranch(value: string): string | null {
    if (!value) return 'Output Branch is required'
    if (value.length < 2) return 'Must be at least 2 characters'
    if (value.length > 255) return 'Must be 255 characters or fewer'
    if (forbiddenBranches.includes(value.toLowerCase())) return 'Cannot use main, master, or default branch'
    if (!gitBranchPattern.test(value)) return 'Must start with alphanumeric, contain only letters, numbers, dots, hyphens, underscores, or slashes'
    if (value.includes('..')) return 'Cannot contain consecutive dots'
    if (value.endsWith('.') || value.endsWith('/') || value.endsWith('-')) return 'Cannot end with dot, slash, or hyphen'
    return null
  }

  function handleOutputBranchChange(value: string) {
    setOutputBranch(value)
    setOutputBranchError(validateOutputBranch(value))
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    const branchErr = validateOutputBranch(outputBranch)
    setOutputBranchError(branchErr)
    if (branchErr) return
    if (!name || !manifestPath) return

    const manifestRepo = repos.find((r) => r.id === manifestRepoId)
    const manifestSourceUrl = manifestRepo ? `${manifestRepo.url}#${manifestPath}` : ''

    const payload = {
      name,
      manifest_source_url: manifestSourceUrl,
      output_branch: outputBranch || null,
      enabled,
      description: description || null,
    }

    if (isEdit) {
      updatePipeline.mutate(payload, {
        onSuccess: () => navigate(`/pipelines/${id}`, { replace: true }),
      })
    } else {
      createPipeline.mutate(payload, {
        onSuccess: () => navigate(`/projects/${projId}`, { replace: true }),
      })
    }
  }
 
  return (
    <div className="mx-auto max-w-lg">
      <Breadcrumb items={
        isEdit
          ? [
              { label: 'Dashboard', href: '/' },
              { label: 'Projects', href: '/projects' },
              { label: project?.name ?? '...', href: `/projects/${pipeline?.project_id}` },
              { label: 'Pipelines' },
              { label: pipeline?.name ?? '...', href: `/pipelines/${id}` },
              { label: 'Edit' },
            ]
          : [
              { label: 'Dashboard', href: '/' },
              { label: 'Projects', href: '/projects' },
              { label: project?.name ?? '...', href: `/projects/${projId}` },
              { label: 'New Pipeline' },
            ]
      } />
 
      <h1 className="mb-6 text-2xl font-bold">
        {isEdit ? 'Edit Pipeline' : 'New Pipeline'}
      </h1>
 
      <Card>
        <CardContent className="p-4">
          <form onSubmit={handleSubmit} className="flex flex-col gap-4">
            {project && (
              <div className="text-sm text-muted-foreground">
                Project: <span className="font-medium text-foreground">{project.name}</span>
              </div>
            )}
            <label className="flex flex-col gap-1 text-sm font-medium">
              Name *
              <input
                className="rounded-md border border-input bg-background px-3 py-2"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
              />
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Description
              <textarea
                className="rounded-md border border-input bg-background px-3 py-2 text-sm"
                value={description}
                onChange={(e) => {
                  if (e.target.value.length <= 500) setDescription(e.target.value)
                }}
                rows={2}
                maxLength={500}
                placeholder="Optional pipeline description"
              />
              <p className="text-xs text-muted-foreground">
                {description.length}/500 characters
              </p>
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Code Repository
              <select
                className="rounded-md border border-input bg-background px-3 py-2 text-sm"
                value={repoId}
                onChange={(e) => setRepoId(e.target.value)}
              >
                <option value="">Select a repository...</option>
                {repos.map((r) => (
                  <option key={r.id} value={r.id}>
                    {r.name} — {r.url}
                  </option>
                ))}
              </select>
              <p className="text-xs text-muted-foreground">
                Source code repository this pipeline operates on
              </p>
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Path to code
              <input
                className="rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
                value={codePath}
                onChange={(e) => setCodePath(e.target.value)}
                placeholder="e.g. services/api (leave empty for root)"
              />
              <p className="text-xs text-muted-foreground">
                 Path within the repository (monorepo support, empty = root)
              </p>
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Manifest Repository
              <select
                className="rounded-md border border-input bg-background px-3 py-2 text-sm"
                value={manifestRepoId}
                onChange={(e) => setManifestRepoId(e.target.value)}
              >
                <option value="">Select manifest repository...</option>
                {repos.map((r) => (
                  <option key={r.id} value={r.id}>
                    {r.name} — {r.url}
                  </option>
                ))}
              </select>
              <p className="text-xs text-muted-foreground">
                Git repository where pipeline manifests are stored
              </p>
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Manifest Path *
              <input
                className="rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
                value={manifestPath}
                onChange={(e) => setManifestPath(e.target.value)}
                placeholder="manifests/doc-quality/"
                required
              />
              <p className="text-xs text-muted-foreground">
                Path within the manifest repository (e.g. manifests/pipeline-name/)
              </p>
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Output Branch *
              <input
                className="rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
                value={outputBranch}
                onChange={(e) => handleOutputBranchChange(e.target.value)}
                placeholder="doc-fix"
                required
              />
              {outputBranchError && (
                <p className="text-xs text-destructive">{outputBranchError}</p>
              )}
              <p className="text-xs text-muted-foreground">
                Branch suffix for pipeline output. Cannot be main, master, or default.
              </p>
            </label>
 
            <label className="flex items-center gap-2 text-sm font-medium">
              <input
                type="checkbox"
                checked={enabled}
                onChange={(e) => setEnabled(e.target.checked)}
                className="accent-primary"
              />
              Enabled
            </label>
 
            <div className="flex items-center justify-between">
              <div className="flex gap-2">
                <Button type="submit" disabled={!name || !manifestRepoId || !manifestPath || !outputBranch || createPipeline.isPending || updatePipeline.isPending}>
                  {(createPipeline.isPending || updatePipeline.isPending) && (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  )}
                  {createPipeline.isPending || updatePipeline.isPending
                    ? (isEdit ? 'Saving...' : 'Creating...')
                    : (isEdit ? 'Save Changes' : 'Create Pipeline')
                  }
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => isEdit ? navigate(`/pipelines/${id}`) : navigate(`/projects/${projId}`)}
                >
                  Cancel
                </Button>
              </div>
              {isEdit && (
                <Button
                  type="button"
                  variant="destructive"
                  onClick={() => setShowDelete(true)}
                >
                  Delete
                </Button>
              )}
            </div>
          </form>
        </CardContent>
      </Card>
 
      <ConfirmDialog
        open={showDelete}
        title="Delete pipeline"
        message={`Are you sure you want to delete '${pipeline?.name ?? 'this pipeline'}'?`}
        onConfirm={() => {
          if (id) {
            deletePipeline.mutate(id, {
              onSuccess: () => navigate(`/projects/${pipeline?.project_id ?? ''}`, { replace: true }),
            })
          }
          setShowDelete(false)
        }}
        onCancel={() => setShowDelete(false)}
      />
    </div>
  )
}