From 2ea71a5a1a0cf0598f1dae110d9144462d456df6 Mon Sep 17 00:00:00 2001 From: BertMarti <107127310+BertMarti@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:31:38 +0200 Subject: [PATCH 1/7] =?UTF-8?q?feat:=20errores=20de=20la=20API=20en=20espa?= =?UTF-8?q?=C3=B1ol=20y=20accionables;=20commitling=20workflow;=20push=20c?= =?UTF-8?q?on=20aviso=20de=20permisos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Mensajes de error que dicen qué hacer: usuario inexistente (404), token rechazado (401), 403 de permisos, límite de peticiones (con y sin token, con la hora de reinicio) y caídas 5xx. Nunca incluyen el token (test). - Dentro de GitHub Actions el error fatal sale también como anotación ::error (escapada, de una línea) para verse en el resumen de la ejecución. - Pista del login no válido («quita la @», vacío, demasiado largo...). - generate.Install: workflow + README para light, dark o both (claro y oscuro con ); Workflow se apoya en ella. Nuevo subcomando `commitling workflow` (alias init) que lo imprime. - El workflow de ejemplo explica en el propio log por qué falla el push (permissions: contents: write o rama protegida). README y USO al día. La interfaz de action.yml no cambia. Hecho por Claude. Co-Authored-By: Claude Opus 5.5 --- README.md | 7 +- cmd/commitling/main.go | 51 ++++++++++++- cmd/commitling/main_test.go | 36 +++++++++ docs/USO.md | 18 +++-- internal/events/events.go | 15 ++++ internal/gallery/gallery.go | 7 +- internal/generate/generate.go | 116 ++++++++++++++++++++++------- internal/generate/generate_test.go | 61 ++++++++++++++- internal/github/client.go | 49 ++++++++++-- internal/github/github_test.go | 55 +++++++++++++- 10 files changed, 365 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index 4b9a2e7..2e3247c 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ jobs: - uses: BertMarti/commitling@v1 with: out: commitling.svg - - name: Guardar el SVG si ha cambiado + - name: Guardar la criatura si ha cambiado run: | git add commitling.svg if git diff --cached --quiet; then @@ -70,7 +70,10 @@ jobs: git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git commit -m "chore: actualiza commitling" - git push + if ! git push; then + echo "::error title=commitling::No se pudo guardar la criatura en el repositorio. Comprueba que este archivo tiene «permissions: contents: write» y, si la rama está protegida, deja que github-actions[bot] suba cambios." + exit 1 + fi ``` 3. Añade la criatura a tu `README.md`: diff --git a/cmd/commitling/main.go b/cmd/commitling/main.go index 08c4fc3..6e3ba09 100644 --- a/cmd/commitling/main.go +++ b/cmd/commitling/main.go @@ -3,6 +3,7 @@ // // commitling render --user [--theme light|dark] [--species moss|mushroom] [--size full|compact] [--keep-on-error] [--now RFC3339] --out commitling.svg // commitling render --fixture testdata/events.json --out commitling.svg +// commitling workflow --user [--species moss|mushroom] [--theme light|dark|both] [--size full|compact] // commitling gallery --out site/ // commitling og --out og.png // commitling version @@ -34,10 +35,15 @@ const usage = `commitling: una mascota pixel-art que crece con tus commits. Uso: commitling render --user [--theme light|dark] [--species moss|mushroom] [--size full|compact] [--keep-on-error] [--now RFC3339] --out commitling render --fixture [--user ] [--theme light|dark] [--species moss|mushroom] [--size full|compact] [--now RFC3339] --out + commitling workflow [--user ] [--species moss|mushroom] [--theme light|dark|both] [--size full|compact] commitling gallery --out commitling og --out commitling version + workflow escribe el archivo .github/workflows/commitling.yml listo para tu + repositorio de perfil (con --theme both, claro y oscuro) y te dice qué poner + en tu README.md. Lo mismo, con botones, en https://bertmarti.github.io/commitling/#instalar + Variables de entorno: GITHUB_TOKEN token opcional para la API de GitHub (más límite de peticiones) ` @@ -48,6 +54,7 @@ var newClient = github.NewClient func main() { if err := run(os.Args[1:], os.Stdout, os.Stderr); err != nil { fmt.Fprintln(os.Stderr, "commitling:", err) + annotate(os.Stdout, err) var ue usageError if errors.As(err, &ue) { os.Exit(2) @@ -56,6 +63,20 @@ func main() { } } +// annotate repeats a fatal error as a GitHub Actions annotation, so it shows +// in the summary of the run and not only deep inside the log of the step. +func annotate(stdout io.Writer, err error) { + if os.Getenv("GITHUB_ACTIONS") != "true" { + return + } + fmt.Fprintln(stdout, "::error title=commitling::"+escapeCommand(err.Error())) +} + +// escapeCommand escapes the data of a workflow command (one line). +func escapeCommand(s string) string { + return strings.NewReplacer("%", "%25", "\r", "%0D", "\n", "%0A").Replace(s) +} + type usageError struct{ msg string } func (e usageError) Error() string { return e.msg } @@ -68,6 +89,8 @@ func run(args []string, stdout, stderr io.Writer) error { switch args[0] { case "render": return runRender(args[1:], stdout, stderr) + case "workflow", "init": + return runWorkflow(args[1:], stdout, stderr) case "gallery": return runGallery(args[1:], stdout, stderr) case "og": @@ -171,7 +194,7 @@ func warnKept(stdout, stderr io.Writer, out string, cause error) { msg := fmt.Sprintf("la API de GitHub no responde (%v); se conserva %s sin cambios", cause, out) fmt.Fprintln(stderr, "commitling: aviso:", msg) if os.Getenv("GITHUB_ACTIONS") == "true" { - fmt.Fprintln(stdout, "::warning title=commitling::"+strings.NewReplacer("%", "%25", "\r", "%0D", "\n", "%0A").Replace(msg)) + fmt.Fprintln(stdout, "::warning title=commitling::"+escapeCommand(msg)) } } @@ -226,6 +249,32 @@ func writeFile(path string, data []byte) error { return nil } +// runWorkflow prints the workflow for a profile repository (the same text as +// the generator of the website) and, on stderr, where to put it. +func runWorkflow(args []string, stdout, stderr io.Writer) error { + fs := flag.NewFlagSet("workflow", flag.ContinueOnError) + fs.SetOutput(stderr) + user := fs.String("user", "", "usuario de GitHub (por defecto, el dueño del repositorio donde corre el workflow)") + speciesFlag := fs.String("species", "moss", "especie: moss (brote de musgo) o mushroom (hongo)") + theme := fs.String("theme", "light", "tema: light, dark o both (claro y oscuro, según quien mire tu perfil)") + sizeFlag := fs.String("size", "full", "tamaño: full (480x200) o compact (insignia de 200x60)") + if err := fs.Parse(args); err != nil { + return usageError{err.Error()} + } + if fs.NArg() > 0 { + return usageError{fmt.Sprintf("argumentos de más: %s", strings.Join(fs.Args(), " "))} + } + setup, err := generate.Install(generate.Options{User: *user, Species: *speciesFlag, Theme: *theme, Size: *sizeFlag}) + if err != nil { + return usageError{err.Error()} + } + if _, err := io.WriteString(stdout, setup.Workflow); err != nil { + return err + } + fmt.Fprintf(stderr, "\nGuárdalo como .github/workflows/commitling.yml en tu repositorio de perfil, añade esto a tu README.md:\n\n%s\n\ny lánzalo una vez en Actions → commitling → Run workflow.\n", setup.Readme) + return nil +} + func runGallery(args []string, stdout, stderr io.Writer) error { fs := flag.NewFlagSet("gallery", flag.ContinueOnError) fs.SetOutput(stderr) diff --git a/cmd/commitling/main_test.go b/cmd/commitling/main_test.go index af708ad..d744a84 100644 --- a/cmd/commitling/main_test.go +++ b/cmd/commitling/main_test.go @@ -492,3 +492,39 @@ func TestWriteFileIsAtomicAndLeavesNoTemporaryFiles(t *testing.T) { } } } + +// commitling workflow prints the same text as generate.Install and says where +// to put it; a wrong value is a usage error. +func TestWorkflowCommand(t *testing.T) { + var stdout, stderr bytes.Buffer + if err := run([]string{"workflow", "--user", "octocat", "--theme", "both", "--species", "mushroom"}, &stdout, &stderr); err != nil { + t.Fatal(err) + } + want, _ := generate.Install(generate.Options{User: "octocat", Theme: "both", Species: "mushroom"}) + if stdout.String() != want.Workflow { + t.Errorf("stdout differs from generate.Install:\n%s", stdout.String()) + } + if !strings.Contains(stderr.String(), ".github/workflows/commitling.yml") || !strings.Contains(stderr.String(), want.Readme) { + t.Errorf("stderr does not explain where to put it:\n%s", stderr.String()) + } + var ue usageError + if err := run([]string{"workflow", "--user", "@octocat"}, &stdout, &stderr); !errors.As(err, &ue) || !strings.Contains(err.Error(), "quita la @") { + t.Errorf("@octocat: %v", err) + } +} + +// Inside GitHub Actions a fatal error is also an annotation (one line, so a +// message cannot open a second workflow command). +func TestAnnotateOnlyInsideActions(t *testing.T) { + var out bytes.Buffer + t.Setenv("GITHUB_ACTIONS", "") + annotate(&out, errors.New("x")) + if out.Len() != 0 { + t.Errorf("outside Actions: %q", out.String()) + } + t.Setenv("GITHUB_ACTIONS", "true") + annotate(&out, errors.New("50% mal\n::set-output name=x::y")) + if got := out.String(); got != "::error title=commitling::50%25 mal%0A::set-output name=x::y\n" { + t.Errorf("annotation = %q", got) + } +} diff --git a/docs/USO.md b/docs/USO.md index 0b89eeb..ebd0c4e 100644 --- a/docs/USO.md +++ b/docs/USO.md @@ -86,7 +86,7 @@ jobs: - uses: BertMarti/commitling@v1 with: out: commitling.svg - - name: Guardar el SVG si ha cambiado + - name: Guardar la criatura si ha cambiado run: | git add commitling.svg if git diff --cached --quiet; then @@ -96,7 +96,10 @@ jobs: git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git commit -m "chore: actualiza commitling" - git push + if ! git push; then + echo "::error title=commitling::No se pudo guardar la criatura en el repositorio. Comprueba que este archivo tiene «permissions: contents: write» y, si la rama está protegida, deja que github-actions[bot] suba cambios." + exit 1 + fi ``` 4. Pulsa **Commit changes…** y confirma con **Commit changes**. @@ -213,9 +216,9 @@ Si tu perfil lo ve gente con el tema oscuro de GitHub, puedes ofrecer una imagen out: commitling.svg - uses: BertMarti/commitling@v1 with: - out: commitling-dark.svg theme: dark - - name: Guardar los SVG si han cambiado + out: commitling-dark.svg + - name: Guardar la criatura si ha cambiado run: | git add commitling.svg commitling-dark.svg if git diff --cached --quiet; then @@ -225,7 +228,10 @@ Si tu perfil lo ve gente con el tema oscuro de GitHub, puedes ofrecer una imagen git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git commit -m "chore: actualiza commitling" - git push + if ! git push; then + echo "::error title=commitling::No se pudo guardar la criatura en el repositorio. Comprueba que este archivo tiene «permissions: contents: write» y, si la rama está protegida, deja que github-actions[bot] suba cambios." + exit 1 + fi ``` **b) Cambia la línea de tu README** por este bloque: @@ -413,7 +419,7 @@ Si solo quieres pausarlo sin borrar nada: **Actions → commitling → menú ⋯ ### El workflow falla al guardar con un error de permisos -Verás algo como «Permission denied» o `403` en el paso «Guardar el SVG si ha cambiado». Revisa: +Verás algo como «Permission denied» o `403` en el paso «Guardar la criatura si ha cambiado» (el workflow lo resume como «No se pudo guardar la criatura en el repositorio»). Revisa: 1. Que tu workflow contiene `permissions:` con `contents: write` (está en el ejemplo). 2. Que en el repositorio, **Settings → Actions → General → Workflow permissions**, está marcado **Read and write permissions**. Algunas organizaciones lo limitan a solo lectura y esa opción manda sobre el archivo. diff --git a/internal/events/events.go b/internal/events/events.go index 347fde5..906e859 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -7,6 +7,7 @@ import ( "errors" "io" "sort" + "strings" "time" "github.com/BertMarti/commitling/internal/stats" @@ -143,6 +144,20 @@ func Login(events []Event) string { return logins[0] } +// LoginHint returns a short Spanish hint, in brackets and starting with a +// space, on why s is not a valid login (for error messages). +func LoginHint(s string) string { + switch { + case s == "": + return " (está vacío)" + case strings.HasPrefix(s, "@"): + return " (quita la @ del principio)" + case len(s) > 39: + return " (tiene más de 39 caracteres)" + } + return " (solo letras, números y guiones, sin espacios ni guion al principio)" +} + // ValidLogin reports whether s looks like a GitHub username: 1 to 39 ASCII // letters, digits or dashes, not starting with a dash. It is checked by hand // because a regexp adds half a megabyte to the WebAssembly build. diff --git a/internal/gallery/gallery.go b/internal/gallery/gallery.go index fa16d77..6d0c568 100644 --- a/internal/gallery/gallery.go +++ b/internal/gallery/gallery.go @@ -44,7 +44,7 @@ const DemoUser = generate.DemoUser const WorkflowSnippet = generate.BaseWorkflow // ReadmeSnippet is the line to paste in the profile README. -const ReadmeSnippet = `![commitling](./commitling.svg)` +const ReadmeSnippet = generate.ReadmeSnippet //go:embed index.html.tmpl var indexTmpl string @@ -175,10 +175,7 @@ func Build(dir, version string) (int, error) { LiveUser: LiveUser, Workflow: WorkflowSnippet, Readme: ReadmeSnippet, - ReadmeDrk: ` - - commitling -`, + ReadmeDrk: generate.ReadmePicture, } extras := []struct { diff --git a/internal/generate/generate.go b/internal/generate/generate.go index f9ca0fa..96ff47e 100644 --- a/internal/generate/generate.go +++ b/internal/generate/generate.go @@ -47,7 +47,7 @@ func (o Options) Check() error { return errors.New("tamaño no válido " + strconv.Quote(o.Size) + " (usa full o compact)") } if o.User != "" && !events.ValidLogin(o.User) { - return errors.New("nombre de usuario no válido: " + strconv.Quote(o.User)) + return errors.New("nombre de usuario no válido: " + strconv.Quote(o.User) + events.LoginHint(o.User)) } return nil } @@ -107,7 +107,8 @@ func draw(login string, st stats.Stats, species creature.Species, o Options) (Re } // BaseWorkflow is the workflow for a profile repository; the README and the -// website show this same text (a test keeps them in sync). +// website show this same text (a test keeps them in sync). If the push fails +// (the usual cause is a workflow without write permission) it says what to do. const BaseWorkflow = `name: commitling on: @@ -126,7 +127,7 @@ jobs: - uses: BertMarti/commitling@v1 with: out: commitling.svg - - name: Guardar el SVG si ha cambiado + - name: Guardar la criatura si ha cambiado run: | git add commitling.svg if git diff --cached --quiet; then @@ -136,36 +137,97 @@ jobs: git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" git commit -m "chore: actualiza commitling" - git push + if ! git push; then + echo "::error title=commitling::No se pudo guardar la criatura en el repositorio. Comprueba que este archivo tiene «permissions: contents: write» y, si la rama está protegida, deja que github-actions[bot] suba cambios." + exit 1 + fi ` -// Workflow returns BaseWorkflow with the inputs of the Action filled in: -// user, and species, theme and size when they are not the defaults. Everything is -// validated first, so nothing that is not a plain login or a known value is -// ever pasted into the YAML. -func Workflow(o Options) (string, error) { - if err := o.Check(); err != nil { - return "", err - } - var inputs strings.Builder - line := func(k, v string) { inputs.WriteString(" " + k + ": " + v + "\n") } - if o.User != "" { - // Always a quoted string: YAML would read 007 as a number and null or - // true as nothing or a boolean. A valid login only has letters, digits - // and dashes, so Go quoting is also valid YAML quoting. - line("user", strconv.Quote(o.User)) +// baseStep is the step of BaseWorkflow that Install fills in or repeats. +const baseStep = " - uses: BertMarti/commitling@v1\n with:\n out: commitling.svg\n" + +// ReadmeSnippet is the line to paste in the profile README for one card. +const ReadmeSnippet = `![commitling](./commitling.svg)` + +// ReadmePicture is the README fragment for the light and dark cards: GitHub +// shows the one that matches the theme of whoever visits the profile. +const ReadmePicture = ` + + commitling +` + +// ThemeBoth asks Install for the light and the dark card at once. +const ThemeBoth = "both" + +// Setup is everything a person pastes into a profile repository. +type Setup struct { + Workflow string // the content of .github/workflows/commitling.yml + Readme string // what goes in README.md + Files []string // the SVG files that the workflow writes and commits +} + +// Install fills in BaseWorkflow with the inputs of the Action: user, and +// species, theme and size when they are not the defaults. Theme may also be +// ThemeBoth: two steps (light and dark) and a for the README. +// Everything is validated first, so nothing that is not a plain login or a +// known value is ever pasted into the YAML. The website builds the same text +// in JavaScript (install.js) and a test keeps both identical. +func Install(o Options) (Setup, error) { + both := strings.EqualFold(strings.TrimSpace(o.Theme), ThemeBoth) + if both { + o.Theme = render.Light.Name } - if sp, _ := creature.SpeciesByName(o.speciesName()); sp != creature.MossSprout { - line("species", sp.Slug()) + if err := o.Check(); err != nil { + if _, ok := render.ThemeByName(o.themeName()); !ok { + return Setup{}, errors.New("tema no válido " + strconv.Quote(o.Theme) + " (usa light, dark o both)") + } + return Setup{}, err } - // The canonical name, not the raw text (spaces, capitals, line breaks). - if theme, _ := render.ThemeByName(o.themeName()); theme.Name != render.Light.Name { - line("theme", theme.Name) + species, _ := creature.SpeciesByName(o.speciesName()) + size, _ := render.SizeByName(o.Size) + step := func(theme render.Theme, out string) string { + var b strings.Builder + line := func(k, v string) { b.WriteString(" " + k + ": " + v + "\n") } + b.WriteString(" - uses: BertMarti/commitling@v1\n with:\n") + if o.User != "" { + // Always a quoted string: YAML would read 007 as a number and null or + // true as nothing or a boolean. A valid login only has letters, digits + // and dashes, so Go quoting is also valid YAML quoting. + line("user", strconv.Quote(o.User)) + } + if species != creature.MossSprout { + line("species", species.Slug()) + } + // The canonical name, not the raw text (spaces, capitals, line breaks). + if theme.Name != render.Light.Name { + line("theme", theme.Name) + } + if size == render.Compact { + line("size", "compact") + } + line("out", out) + return b.String() } - if size, _ := render.SizeByName(o.Size); size == render.Compact { - line("size", "compact") + s := Setup{Readme: ReadmeSnippet, Files: []string{"commitling.svg"}} + var steps string + if both { + s.Readme = ReadmePicture + s.Files = append(s.Files, "commitling-dark.svg") + steps = step(render.Light, s.Files[0]) + step(render.Dark, s.Files[1]) + } else { + theme, _ := render.ThemeByName(o.themeName()) + steps = step(theme, s.Files[0]) } - return strings.Replace(BaseWorkflow, " with:\n", " with:\n"+inputs.String(), 1), nil + s.Workflow = strings.Replace(BaseWorkflow, baseStep, steps, 1) + s.Workflow = strings.Replace(s.Workflow, "git add commitling.svg\n", "git add "+strings.Join(s.Files, " ")+"\n", 1) + return s, nil +} + +// Workflow is the workflow of Install (the live generator of the website asks +// for one card at a time). +func Workflow(o Options) (string, error) { + s, err := Install(o) + return s.Workflow, err } // FetchError explains in Spanish why the browser could not read the events of diff --git a/internal/generate/generate_test.go b/internal/generate/generate_test.go index de74bcc..0e4d669 100644 --- a/internal/generate/generate_test.go +++ b/internal/generate/generate_test.go @@ -189,7 +189,7 @@ func TestCheckMessagesAreTheOnesOfTheCLI(t *testing.T) { if err := (Options{Species: "dragon"}).Check(); err == nil || err.Error() != `especie no válida "dragon" (usa moss o mushroom)` { t.Errorf("species: %v", err) } - if err := (Options{User: "a b"}).Check(); err == nil || err.Error() != `nombre de usuario no válido: "a b"` { + if err := (Options{User: "a b"}).Check(); err == nil || err.Error() != `nombre de usuario no válido: "a b" (solo letras, números y guiones, sin espacios ni guion al principio)` { t.Errorf("user: %v", err) } if err := (Options{User: "BertMarti", Species: "hongo", Theme: "dark"}).Check(); err != nil { @@ -389,3 +389,62 @@ func TestWorkflowWritesSizeOnlyWhenCompact(t *testing.T) { t.Error("an invalid size must be rejected before it reaches the YAML") } } + +// Install with both themes draws two cards and the README picks one with +// ; with one theme it is Workflow. +func TestInstall(t *testing.T) { + plain, err := Install(Options{}) + if err != nil || plain.Workflow != BaseWorkflow || plain.Readme != ReadmeSnippet || len(plain.Files) != 1 { + t.Fatalf("defaults: %+v, %v", plain, err) + } + if !strings.Contains(BaseWorkflow, baseStep) { + t.Fatal("BaseWorkflow lost the step that Install fills in") + } + both, err := Install(Options{User: "octocat", Species: "hongo", Theme: " Both ", Size: "compact"}) + if err != nil { + t.Fatal(err) + } + if both.Readme != ReadmePicture || strings.Join(both.Files, " ") != "commitling.svg commitling-dark.svg" { + t.Errorf("both: readme %q, files %v", both.Readme, both.Files) + } + for _, want := range []string{ + " species: mushroom\n size: compact\n out: commitling.svg\n", + " species: mushroom\n theme: dark\n size: compact\n out: commitling-dark.svg\n", + "git add commitling.svg commitling-dark.svg\n", + } { + if !strings.Contains(both.Workflow, want) { + t.Errorf("both lacks %q:\n%s", want, both.Workflow) + } + } + if n := strings.Count(both.Workflow, "uses: BertMarti/commitling@v1"); n != 2 { + t.Errorf("both uses the Action %d times, want 2", n) + } + if n := strings.Count(both.Workflow, `user: "octocat"`); n != 2 { + t.Errorf("both writes the user %d times, want 2", n) + } + for _, th := range []string{"light", "dark"} { + s, _ := Install(Options{User: "octocat", Theme: th}) + w, _ := Workflow(Options{User: "octocat", Theme: th}) + if s.Workflow != w || s.Readme != ReadmeSnippet { + t.Errorf("%s: Install and Workflow differ", th) + } + } + if _, err := Install(Options{Theme: "sepia"}); err == nil || !strings.Contains(err.Error(), "both") { + t.Errorf("a wrong theme should mention both: %v", err) + } + if _, err := Install(Options{Theme: "both", User: "x\nrun: evil"}); err == nil { + t.Error("both must still validate the user") + } +} + +// The push step explains, inside the run, what to do when it is not allowed. +func TestBaseWorkflowExplainsAFailedPush(t *testing.T) { + for _, want := range []string{"permissions:\n contents: write\n", "if ! git push; then", "::error title=commitling::", "contents: write"} { + if !strings.Contains(BaseWorkflow, want) { + t.Errorf("BaseWorkflow lacks %q", want) + } + } + if strings.Contains(BaseWorkflow, "${{") { + t.Error("no expressions in the workflow that people paste") + } +} diff --git a/internal/github/client.go b/internal/github/client.go index 7b06973..76f86a9 100644 --- a/internal/github/client.go +++ b/internal/github/client.go @@ -92,6 +92,12 @@ type APIError struct { // RateLimited is set on a 403 that carries rate-limit headers (a plain // 403 is a permissions problem). RateLimited bool + // User is the login that was asked for ("" when unknown). + User string + // Reset is when the rate limit is restored (zero when GitHub did not say). + Reset time.Time + // Authenticated tells whether the request carried a token. + Authenticated bool } // IsTransient reports whether err is a failure that may pass by itself: no @@ -117,12 +123,38 @@ func rateLimitHeaders(hdr http.Header) bool { func (e *APIError) Error() string { return e.baseError() + retriesSuffix(e.Retries) } +// baseError explains the failure in Spanish and says what to do. It never +// includes the token: only the status, GitHub's own message and the login. func (e *APIError) baseError() string { + who := "ese usuario" + if e.User != "" { + who = "el usuario «" + e.User + "»" + } switch { case e.Status == http.StatusNotFound: - return "usuario no encontrado en GitHub (404)" - case e.Status == http.StatusForbidden || e.Status == http.StatusTooManyRequests: - return fmt.Sprintf("la API de GitHub ha rechazado la petición (%d): %s; si es el límite de peticiones, define GITHUB_TOKEN", e.Status, e.Message) + return fmt.Sprintf("%s no existe en GitHub (404). Revisa la entrada user del workflow (o --user): "+ + "es tu nombre de usuario tal y como aparece en github.com/, sin @ ni espacios", who) + case e.Status == http.StatusUnauthorized: + return "GitHub no acepta el token (401: " + e.Message + "). Si pasas un token propio en la entrada token, " + + "comprueba que no ha caducado o quita esa entrada para usar el GITHUB_TOKEN del workflow; " + + "en la línea de órdenes, revisa o borra la variable GITHUB_TOKEN" + case e.Status == http.StatusTooManyRequests || e.RateLimited: + msg := fmt.Sprintf("se ha agotado el límite de peticiones de la API de GitHub (%d)", e.Status) + if !e.Reset.IsZero() { + msg += ". Se restablece a las " + e.Reset.UTC().Format("15:04") + " UTC" + } + if e.Authenticated { + return msg + ". Con keep-on-error: true (la opción por defecto de la Action) se conserva la criatura anterior " + + "y se vuelve a intentar en la siguiente ejecución; si pasa a menudo, cambia la hora del cron para no coincidir con otros workflows" + } + return msg + ". Sin token solo hay 60 peticiones por hora: en la Action no quites la entrada token " + + "(por defecto usa el GITHUB_TOKEN del workflow) y en la línea de órdenes define la variable GITHUB_TOKEN" + case e.Status == http.StatusForbidden: + return "GitHub ha denegado el acceso (403: " + e.Message + "). Si pasas un token propio en la entrada token, " + + "comprueba sus permisos o quita esa entrada para usar el GITHUB_TOKEN del workflow" + case e.Status >= 500: + return fmt.Sprintf("GitHub no responde bien ahora mismo (%d: %s). Es pasajero: vuelve a lanzar el workflow "+ + "dentro de unos minutos (con keep-on-error: true se conserva la criatura anterior)", e.Status, e.Message) default: return fmt.Sprintf("la API de GitHub respondió %d: %s", e.Status, e.Message) } @@ -132,7 +164,7 @@ func (e *APIError) baseError() string { // the last 90 days) of user, newest first. func (c *Client) FetchEvents(ctx context.Context, user string) ([]Event, error) { if !ValidLogin(user) { - return nil, fmt.Errorf("nombre de usuario no válido: %q", user) + return nil, fmt.Errorf("nombre de usuario no válido: %q%s", user, events.LoginHint(user)) } var all []Event for page := 1; page <= maxPages; page++ { @@ -359,8 +391,13 @@ func (c *Client) doPage(ctx context.Context, user string, page int) ([]Event, ht if msg.Message == "" { msg.Message = http.StatusText(resp.StatusCode) } - return nil, resp.Header, &APIError{Status: resp.StatusCode, Message: msg.Message, - RateLimited: resp.StatusCode == http.StatusForbidden && rateLimitHeaders(resp.Header)} + apiErr := &APIError{Status: resp.StatusCode, Message: msg.Message, User: user, + RateLimited: resp.StatusCode == http.StatusForbidden && rateLimitHeaders(resp.Header), + Authenticated: c.Token != ""} + if unix, err := strconv.ParseInt(strings.TrimSpace(resp.Header.Get("X-RateLimit-Reset")), 10, 64); err == nil && unix > 0 && unix < 1<<40 { + apiErr.Reset = time.Unix(unix, 0) + } + return nil, resp.Header, apiErr } events, err := ParseEvents(resp.Body) return events, resp.Header, err diff --git a/internal/github/github_test.go b/internal/github/github_test.go index bcc79fd..f73703f 100644 --- a/internal/github/github_test.go +++ b/internal/github/github_test.go @@ -192,8 +192,9 @@ func TestFetchEventsErrors(t *testing.T) { body string want string }{ - {http.StatusNotFound, `{"message":"Not Found"}`, "no encontrado"}, - {http.StatusForbidden, `{"message":"API rate limit exceeded"}`, "GITHUB_TOKEN"}, + {http.StatusNotFound, `{"message":"Not Found"}`, "«octoexample» no existe en GitHub (404)"}, + {http.StatusForbidden, `{"message":"Resource not accessible"}`, "quita esa entrada"}, + {http.StatusUnauthorized, `{"message":"Bad credentials"}`, "401: Bad credentials"}, {http.StatusInternalServerError, `oops`, "500"}, } for _, c := range cases { @@ -380,3 +381,53 @@ func TestFetchEventsDropsOverlapBetweenPages(t *testing.T) { t.Fatalf("got %d events, want 104", len(events)) } } + +// The messages say what to do, in Spanish, and depend on whether the request +// carried a token; none of them ever shows the token itself. +func TestAPIErrorsAreActionableAndNeverShowTheToken(t *testing.T) { + const secret = "ghp_EsteTokenNoDebeVerseNunca0123456789" + reset := time.Date(2026, 10, 24, 13, 45, 0, 0, time.UTC) + cases := []struct { + name string + token string + status int + headers map[string]string + want []string + }{ + {"404", secret, 404, nil, []string{"no existe en GitHub", "entrada user", "sin @"}}, + {"401", secret, 401, nil, []string{"GitHub no acepta el token", "entrada token", "GITHUB_TOKEN"}}, + {"403 plain", secret, 403, nil, []string{"denegado", "entrada token"}}, + {"límite con token", secret, 403, map[string]string{"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": fmt.Sprint(reset.Unix())}, + []string{"límite de peticiones", "13:45 UTC", "keep-on-error"}}, + {"límite sin token", "", 429, nil, []string{"límite de peticiones", "60 peticiones por hora", "GITHUB_TOKEN"}}, + {"5xx", secret, 503, nil, []string{"no responde bien", "503", "dentro de unos minutos"}}, + } + for _, c := range cases { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + for k, v := range c.headers { + w.Header().Set(k, v) + } + w.WriteHeader(c.status) + // GitHub never echoes the token, but a hostile proxy could: it must + // not reach the log through the message either way. + fmt.Fprint(w, `{"message":"x"}`) + })) + cl := NewClient(c.token) + cl.BaseURL = srv.URL + cl.MaxWait = time.Millisecond // do not wait for the reset + cl.Sleep = func(context.Context, time.Duration) error { return nil } + _, err := cl.FetchEvents(context.Background(), "octoexample") + srv.Close() + if err == nil { + t.Fatalf("%s: expected an error", c.name) + } + for _, w := range c.want { + if !strings.Contains(err.Error(), w) { + t.Errorf("%s: %q does not mention %q", c.name, err, w) + } + } + if strings.Contains(err.Error(), secret) || strings.Contains(err.Error(), "Bearer") { + t.Errorf("%s: the error shows the token: %q", c.name, err) + } + } +} From 76cc16883ca1eb633764502c6d80c40589a3def5 Mon Sep 17 00:00:00 2001 From: BertMarti <107127310+BertMarti@users.noreply.github.com> Date: Sat, 24 Oct 2026 15:12:23 +0200 Subject: [PATCH 2/7] ci(seguridad): la Action enmascara el token; actionlint valida los workflows generados MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - action.yml: ::add-mask:: del token antes de ejecutar nada (defensa en profundidad para un token pegado en claro). Sin cambios en la interfaz. Test TestActionMasksTheToken. - action-test: un usuario inexistente falla aunque keep-on-error esté activa. - CI: genera los 13 workflows posibles con `commitling workflow`, exige @v1 y los valida con actionlint 1.7.12 (binario oficial con SHA-256 fijado, con shellcheck) junto con los workflows del repositorio. Hecho por Claude. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/action-test.yml | 13 +++++++++++++ .github/workflows/ci.yml | 27 +++++++++++++++++++++++++++ action.yml | 3 +++ internal/gallery/action_test.go | 20 ++++++++++++++++++++ 4 files changed, 63 insertions(+) diff --git a/.github/workflows/action-test.yml b/.github/workflows/action-test.yml index 0da97e8..2aa0ca4 100644 --- a/.github/workflows/action-test.yml +++ b/.github/workflows/action-test.yml @@ -74,6 +74,16 @@ jobs: out: out/real-dark.svg theme: dark + # Un usuario que no existe es un error permanente: falla aunque + # keep-on-error esté activada, con el mensaje «no existe en GitHub». + - name: Un usuario inexistente falla con un error claro + id: nouser + continue-on-error: true + uses: ./ + with: + user: commitling-usuario-que-no-existe-0 + out: out/nouser.svg + # keep-on-error (activada por defecto) solo conserva el SVG ante fallos # transitorios (red, 5xx, límite de peticiones), que cubren los tests de # la CLI. Un 401 (token inválido) es permanente: debe fallar aunque haya @@ -120,6 +130,7 @@ jobs: INVALID_OUTCOME: ${{ steps.invalid.outcome }} UNAUTHORIZED_OUTCOME: ${{ steps.unauthorized.outcome }} BADKEEP_OUTCOME: ${{ steps.badkeep.outcome }} + NOUSER_OUTCOME: ${{ steps.nouser.outcome }} OWNER: ${{ github.repository_owner }} run: | set -euo pipefail @@ -130,6 +141,8 @@ jobs: test "$UNAUTHORIZED_OUTCOME" = failure || { echo 'un 401 debería fallar aunque haya SVG previo'; exit 1; } test "$BADKEEP_OUTCOME" = failure || { echo 'keep-on-error: quizas debería fallar'; exit 1; } test ! -e out/badkeep.svg + test "$NOUSER_OUTCOME" = failure || { echo 'un usuario inexistente debería fallar'; exit 1; } + test ! -e out/nouser.svg cmp out/keep.svg "$FIXTURE_PATH" || { echo 'el SVG previo cambió'; exit 1; } for f in "$FIXTURE_PATH" "$MUSHROOM_PATH" "$COMPACT_PATH" "$REAL_PATH"; do test -s "$f" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 62b18c1..4ed61ac 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -78,6 +78,33 @@ jobs: - name: versión run: go run ./cmd/commitling version + # Every workflow that the web generator and `commitling workflow` can + # produce (the web builds the same bytes; a test compares them) must be + # a valid GitHub Actions workflow that uses @v1: actionlint (official + # binary, pinned SHA-256) also runs shellcheck on its `run:` script. + - name: workflows generados (actionlint) + if: runner.os == 'Linux' + env: + ACTIONLINT_VERSION: "1.7.12" + ACTIONLINT_SHA256: "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8" + run: | + set -euo pipefail + go build -o "$RUNNER_TEMP/commitling" ./cmd/commitling + mkdir -p out/wf + "$RUNNER_TEMP/commitling" workflow > out/wf/base.yml 2>/dev/null + for sp in moss mushroom; do for th in light dark both; do for sz in full compact; do + "$RUNNER_TEMP/commitling" workflow --user octocat --species "$sp" --theme "$th" --size "$sz" > "out/wf/$sp-$th-$sz.yml" 2>/dev/null + done; done; done + if grep -L 'uses: BertMarti/commitling@v1$' out/wf/*.yml | grep .; then echo "sin @v1"; exit 1; fi + if grep -l 'commitling@main' out/wf/*.yml; then echo "con @main"; exit 1; fi + tgz="actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" + curl -fsSLo "$RUNNER_TEMP/$tgz" "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/$tgz" + echo "${ACTIONLINT_SHA256} $RUNNER_TEMP/$tgz" | sha256sum -c - + tar -xzf "$RUNNER_TEMP/$tgz" -C "$RUNNER_TEMP" actionlint + command -v shellcheck + "$RUNNER_TEMP/actionlint" -color out/wf/*.yml .github/workflows/*.yml + echo "$(ls out/wf/*.yml | wc -l) workflows generados válidos" + # Security checks: known vulnerabilities in Go and its standard library # (govulncheck), static analysis (staticcheck, also for the wasm build) and # secrets in the whole history and the working tree (gitleaks, official diff --git a/action.yml b/action.yml index aeb0cdf..e912216 100644 --- a/action.yml +++ b/action.yml @@ -71,6 +71,9 @@ runs: CL_KEEP_ON_ERROR: ${{ inputs.keep-on-error }} run: | set -euo pipefail + # Defence in depth: GitHub already hides secrets and github.token in + # the logs, but not a token pasted as plain text into `token:`. + if [ -n "${GITHUB_TOKEN:-}" ]; then echo "::add-mask::$GITHUB_TOKEN"; fi abs() { case "$1" in /*|[A-Za-z]:*) printf '%s' "$1" ;; *) printf '%s/%s' "$GITHUB_WORKSPACE" "$1" ;; esac; } out="$(abs "$CL_OUT")" args=(render --theme "$CL_THEME" --species "$CL_SPECIES" --size "$CL_SIZE" --out "$out") diff --git a/internal/gallery/action_test.go b/internal/gallery/action_test.go index 17fa908..cbc7e18 100644 --- a/internal/gallery/action_test.go +++ b/internal/gallery/action_test.go @@ -290,3 +290,23 @@ func TestGoModPinsAPatchedGo(t *testing.T) { } } } + +// The token reaches the script only through the environment and is masked +// before anything runs, so even a token pasted as plain text never shows in +// the log; the script never prints the environment or traces commands. +func TestActionMasksTheToken(t *testing.T) { + yml := readRepoFile(t, "action.yml") + mask := strings.Index(yml, `echo "::add-mask::$GITHUB_TOKEN"`) + run := strings.Index(yml, "go run ./cmd/commitling") + if mask < 0 || run < 0 || mask > run { + t.Fatal("action.yml must mask $GITHUB_TOKEN before go run") + } + if !strings.Contains(yml, "GITHUB_TOKEN: ${{ inputs.token }}") { + t.Error("the token must arrive by env:") + } + for _, bad := range []string{"set -x", "set -o xtrace", "printenv", "env |", "echo \"$GITHUB_TOKEN", "echo $GITHUB_TOKEN"} { + if strings.Contains(yml, bad) { + t.Errorf("action.yml contains %q", bad) + } + } +} From dfc07f2d2902a64d44408666622258b296c64a29 Mon Sep 17 00:00:00 2001 From: BertMarti <107127310+BertMarti@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:26:33 +0200 Subject: [PATCH 3/7] =?UTF-8?q?feat(web):=20generador=20del=20workflow=20e?= =?UTF-8?q?n=20=C2=ABInst=C3=A1lalo=20en=20tu=20perfil=C2=BB;=20CSS=20fuer?= =?UTF-8?q?a=20de=20l=C3=ADnea?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Usuario (o enlace del perfil), especie, tema (claro, oscuro o automático con las dos tarjetas y ) y tamaño → workflow y README listos para copiar, seis pasos para quien nunca ha usado Actions con enlaces directos a GitHub (incluido «Abrir GitHub con el archivo ya relleno») y «Si algo falla» con cada mensaje y qué hacer. Sin JavaScript se ve el workflow base. - install.js: sin red, sin wasm, sin almacenamiento ni innerHTML; produce byte a byte lo mismo que generate.Install (TestInstallJSMatchesGo con las 48 combinaciones) y tiene test de comportamiento en Node con DOM falso. - El CSS pasa a style.css y la CSP queda en style-src 'self' (origen compartido bertmarti.github.io); sin atributos style=. - README y docs/USO.md: el generador como camino fácil, pasos más claros, qué hacer si el workflow sale en rojo; CHANGELOG de 0.8.0. install.js y su test en Node: GPT-5.6 Luna (delegado; el primer intento agotó el tiempo sin entregar), revisado, corregido y completado por Claude (paso de usuario desde el generador, enlaces con consulta, tests de la interfaz). Marcado, CSS, tests en Go y textos: Claude. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 11 +- README.md | 30 ++- docs/USO.md | 11 +- internal/gallery/gallery.go | 18 ++ internal/gallery/gallery_test.go | 42 +++- internal/gallery/generator_test.go | 10 +- internal/gallery/index.html.tmpl | 206 +++++++------------- internal/gallery/install.js | 169 ++++++++++++++++ internal/gallery/install_test.go | 124 ++++++++++++ internal/gallery/style.css | 134 +++++++++++++ internal/gallery/testdata/install.test.js | 224 ++++++++++++++++++++++ 11 files changed, 826 insertions(+), 153 deletions(-) create mode 100644 internal/gallery/install.js create mode 100644 internal/gallery/install_test.go create mode 100644 internal/gallery/style.css create mode 100644 internal/gallery/testdata/install.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 125d0e3..ee430a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,10 +8,16 @@ El formato sigue [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/) y e ## [0.8.0] - 2026-10-24 -Versión «Blindada»: seguridad, documentación y accesibilidad. **`action.yml` no cambia** (mismas entradas, misma salida `path`, mismos archivos) y las tarjetas SVG son byte a byte las de v0.7.0 (las 96 huellas de v0.5.0 pasan). +Versión «Blindada»: seguridad, documentación, accesibilidad y una instalación guiada. **La interfaz de `action.yml` no cambia** (mismas entradas, misma salida `path`, mismos archivos) y las tarjetas SVG son byte a byte las de v0.7.0 (las 96 huellas de v0.5.0 pasan). ### Añadido +- **Generador del workflow en la web** («Instálalo en tu perfil»): escribes tu usuario (o pegas el enlace de tu perfil), eliges especie, tema (claro, oscuro o **automático**, con las dos tarjetas y un ``) y tamaño, y copias el `.github/workflows/commitling.yml` y el fragmento del README ya rellenos. Seis pasos explicados para quien nunca ha usado Actions (repositorio de perfil, crear el archivo, permisos, primera ejecución con «Run workflow», README y resultado), enlaces directos a cada paso en GitHub (incluido «Abrir GitHub con el archivo ya relleno») y una lista «Si algo falla» con cada mensaje y qué hacer. Funciona sin red y sin wasm (`install.js`), no guarda nada y produce byte a byte lo mismo que `generate.Install` (test en Node y Go). +- **`commitling workflow`** (alias `init`): imprime ese mismo workflow (`--user`, `--species`, `--theme light|dark|both`, `--size`) y dice qué pegar en el README. +- **Mensajes de error que dicen qué hacer**, en español: usuario inexistente (404), token rechazado (401), acceso denegado (403), límite de peticiones (con la hora UTC a la que se restablece y si había token) y caídas de GitHub (5xx); el login no válido explica por qué («quita la @ del principio»…). Dentro de GitHub Actions el error sale también como anotación `::error` en el resumen de la ejecución. +- El workflow de ejemplo explica en el propio log por qué falla el `git push` («No se pudo guardar la criatura en el repositorio»: `permissions: contents: write` o rama protegida). El paso se llama ahora «Guardar la criatura si ha cambiado». +- CI: los 13 workflows que pueden generarse se validan con **actionlint** (con shellcheck) y deben usar `@v1`; la prueba de la Action comprueba que un usuario inexistente falla. + - **Content-Security-Policy estricta en la web**: solo scripts propios (más `'wasm-unsafe-eval'` para el generador), conexiones solo a la propia web y a `api.github.com`, sin `object`, `base` ni formularios externos; `referrer` `strict-origin-when-cross-origin` y `theme-color` para claro y oscuro. El script de los botones «Copiar» y el aviso de criatura en vivo no disponible pasan a `page.js` (antes eran un ` + diff --git a/internal/gallery/install.js b/internal/gallery/install.js new file mode 100644 index 0000000..1408ed7 --- /dev/null +++ b/internal/gallery/install.js @@ -0,0 +1,169 @@ +// Workflow generator of «Instálalo en tu perfil». It builds in the browser, +// with no wasm, no network and no storage, the same text as generate.Install +// (a Go test compares both for every option) and fills the steps with direct +// links to GitHub. No HTML is built from what the person types: only +// textContent and validated logins in href. +(function (root) { + 'use strict'; + + var BaseWorkflow = 'name: commitling\n\n' + + 'on:\n' + + ' schedule:\n' + + ' - cron: "23 5 * * *" # cada día a las 05:23 UTC\n' + + ' workflow_dispatch:\n\n' + + 'permissions:\n' + + ' contents: write\n\n' + + 'jobs:\n' + + ' commitling:\n' + + ' runs-on: ubuntu-latest\n' + + ' steps:\n' + + ' - uses: actions/checkout@v7\n' + + ' - uses: BertMarti/commitling@v1\n' + + ' with:\n' + + ' out: commitling.svg\n' + + ' - name: Guardar la criatura si ha cambiado\n' + + ' run: |\n' + + ' git add commitling.svg\n' + + ' if git diff --cached --quiet; then\n' + + ' echo "Sin cambios."\n' + + ' exit 0\n' + + ' fi\n' + + ' git config user.name "github-actions[bot]"\n' + + ' git config user.email "41898282+github-actions[bot]@users.noreply.github.com"\n' + + ' git commit -m "chore: actualiza commitling"\n' + + ' if ! git push; then\n' + + ' echo "::error title=commitling::No se pudo guardar la criatura en el repositorio. Comprueba que este archivo tiene «permissions: contents: write» y, si la rama está protegida, deja que github-actions[bot] suba cambios."\n' + + ' exit 1\n' + + ' fi\n'; + + var ReadmeSnippet = '![commitling](./commitling.svg)'; + var ReadmePicture = '\n' + + ' \n' + + ' commitling\n' + + ''; + + function validLogin(s) { + return typeof s === 'string' && s.length >= 1 && s.length <= 39 && + s.charAt(0) !== '-' && !/[^A-Za-z0-9-]/.test(s); + } + + function normalizeUser(s) { + s = typeof s === 'string' ? s.trim() : ''; + if (s.charAt(0) === '@') s = s.slice(1); + // A pasted profile link: https://github.com/, with or without the + // scheme, a trailing slash, a path, a query or a fragment. + var match = s.match(/^(?:https?:\/\/)?(?:www\.)?github\.com\/([^/?#]+)(?:[/?#].*)?$/i); + return match ? match[1] : s; + } + + function option(value, fallback) { + return typeof value === 'string' && value ? value.trim().toLowerCase() : fallback; + } + + function build(input) { + input = input || {}; + var user = normalizeUser(input.user); + if (!validLogin(user)) user = ''; + var species = option(input.species, 'moss'); + var theme = option(input.theme, 'light'); + var size = option(input.size, 'full'); + var both = theme === 'both'; + var files = both ? ['commitling.svg', 'commitling-dark.svg'] : ['commitling.svg']; + + function step(stepTheme, out) { + var text = ' - uses: BertMarti/commitling@v1\n with:\n'; + if (user) text += ' user: "' + user + '"\n'; + if (species !== 'moss') text += ' species: mushroom\n'; + if (stepTheme === 'dark') text += ' theme: dark\n'; + if (size === 'compact') text += ' size: compact\n'; + return text + ' out: ' + out + '\n'; + } + + var steps = both ? step('light', files[0]) + step('dark', files[1]) : step(theme, files[0]); + var workflow = BaseWorkflow.replace( + ' - uses: BertMarti/commitling@v1\n with:\n out: commitling.svg\n', steps + ).replace('git add commitling.svg\n', 'git add ' + files.join(' ') + '\n'); + return { workflow: workflow, readme: both ? ReadmePicture : ReadmeSnippet, files: files }; + } + + function links(login) { + var encoded = encodeURIComponent(login); + var repo = 'https://github.com/' + encoded + '/' + encoded; + return { + newRepo: 'https://github.com/new?name=' + encoded + '&visibility=public', + newFile: function (workflow) { + return repo + '/new/main?filename=.github%2Fworkflows%2Fcommitling.yml&value=' + encodeURIComponent(workflow); + }, + actions: repo + '/actions/workflows/commitling.yml', + editReadme: repo + '/edit/main/README.md', + profile: 'https://github.com/' + encoded + }; + } + + root.commitlingInstall = { build: build, normalizeUser: normalizeUser, validLogin: validLogin, links: links }; + + if (typeof document === 'undefined') return; + var form = document.getElementById('ins-form'); + if (!form) return; + form.hidden = false; + var userInput = document.getElementById('ins-user'); + var error = document.getElementById('ins-error'); + var workflowEl = document.getElementById('wf'); + var readmeEl = document.getElementById('rd'); + var repoEl = document.getElementById('ins-repo'); + var linkParagraphs = document.querySelectorAll('.ins-link'); + var noLinks = document.getElementById('ins-nolinks'); + + function checked(name, fallback) { + var radios = document.querySelectorAll('input[name="' + name + '"]'); + for (var i = 0; i < radios.length; i++) if (radios[i].checked) return radios[i].value; + return fallback; + } + + function recalculate() { + var login = normalizeUser(userInput.value); + var valid = login === '' || validLogin(login); + var result = build({ user: valid ? login : '', species: checked('ins-species', 'moss'), theme: checked('ins-theme', 'light'), size: checked('ins-size', 'full') }); + workflowEl.textContent = result.workflow; + readmeEl.textContent = result.readme; + repoEl.textContent = login && valid ? login + '/' + login : 'tu-usuario/tu-usuario'; + if (!valid) { + error.textContent = 'Escribe un usuario de GitHub válido: entre 1 y 39 letras, números o guiones, sin guion inicial.'; + userInput.setAttribute('aria-invalid', 'true'); + } else { + error.textContent = ''; + userInput.removeAttribute('aria-invalid'); + } + var show = valid && login !== ''; + for (var i = 0; i < linkParagraphs.length; i++) linkParagraphs[i].hidden = !show; + noLinks.hidden = show; + if (show) { + var urls = links(login); + document.getElementById('ins-new-repo').setAttribute('href', urls.newRepo); + document.getElementById('ins-new-file').setAttribute('href', urls.newFile(result.workflow)); + document.getElementById('ins-actions').setAttribute('href', urls.actions); + document.getElementById('ins-edit-readme').setAttribute('href', urls.editReadme); + document.getElementById('ins-profile').setAttribute('href', urls.profile); + } + } + + form.addEventListener('input', recalculate); + form.addEventListener('change', recalculate); + recalculate(); + var genForm = document.getElementById('gen-form'); + if (genForm) genForm.addEventListener('submit', function () { + var genUser = document.getElementById('gen-user'); + var login = normalizeUser(genUser && genUser.value); + // Only a valid name is carried over: the generator shows its own error. + if (!userInput.value && validLogin(login)) { + userInput.value = login; + var names = [['species', 'ins-species'], ['theme', 'ins-theme'], ['size', 'ins-size']]; + for (var i = 0; i < names.length; i++) { + var source = document.querySelector('input[name="' + names[i][0] + '"]:checked'); + var target = document.querySelector('input[name="' + names[i][1] + '"][value="' + (source ? source.value : '') + '"]'); + if (target) target.checked = true; + } + recalculate(); + } + }); +})(typeof window !== 'undefined' ? window : this); diff --git a/internal/gallery/install_test.go b/internal/gallery/install_test.go new file mode 100644 index 0000000..e8b8f1d --- /dev/null +++ b/internal/gallery/install_test.go @@ -0,0 +1,124 @@ +package gallery + +import ( + "encoding/json" + "os" + "os/exec" + "regexp" + "runtime" + "strings" + "testing" + + "github.com/BertMarti/commitling/internal/generate" +) + +// The workflow generator of «Instálalo en tu perfil» (install.js) builds in +// the browser, without wasm or network, the same text as generate.Install. +// Its behaviour is proved in Node (testdata/install.test.js); here it is +// compared, byte for byte, with Go for every option. + +func nodeOrSkip(t *testing.T) string { + t.Helper() + if runtime.GOOS == "js" { + t.Skip("cannot start node from a wasm test binary") + } + node, err := exec.LookPath("node") + if err != nil { + if os.Getenv("CI") != "" { + t.Fatal("node is not installed, and the CI must run the install test") + } + t.Skip("node is not installed") + } + return node +} + +func TestInstallBehaviourInNode(t *testing.T) { + node := nodeOrSkip(t) + dir := buildDir(t) + out, err := exec.Command(node, "testdata/install.test.js", dir+string(os.PathSeparator)+"install.js").CombinedOutput() + if err != nil { + t.Fatalf("install.test.js failed: %v\n%s", err, out) + } + if n := strings.Count("\n"+string(out), "\nok "); n < 10 { + t.Errorf("expected at least 10 scenarios, got %d:\n%s", n, out) + } +} + +func TestInstallJSMatchesGo(t *testing.T) { + node := nodeOrSkip(t) + dir := buildDir(t) + out, err := exec.Command(node, "testdata/install.test.js", dir+string(os.PathSeparator)+"install.js", "--dump").Output() + if err != nil { + t.Fatalf("install.test.js --dump failed: %v", err) + } + var cases []struct { + User, Species, Theme, Size string + Workflow, Readme string + Files []string + } + if err := json.Unmarshal(out, &cases); err != nil { + t.Fatalf("--dump is not JSON: %v\n%.300s", err, out) + } + if len(cases) != 4*2*3*2 { + t.Fatalf("%d cases, want 48", len(cases)) + } + for _, c := range cases { + want, err := generate.Install(generate.Options{User: c.User, Species: c.Species, Theme: c.Theme, Size: c.Size}) + if err != nil { + t.Fatalf("%+v: %v", c, err) + } + name := c.User + "/" + c.Species + "/" + c.Theme + "/" + c.Size + if c.Workflow != want.Workflow { + t.Errorf("%s: the workflow of install.js differs from Go:\n%s", name, c.Workflow) + } + if c.Readme != want.Readme || strings.Join(c.Files, " ") != strings.Join(want.Files, " ") { + t.Errorf("%s: readme %q files %v, want %q %v", name, c.Readme, c.Files, want.Readme, want.Files) + } + } +} + +// The section is a real form (hidden until the script runs: without it the +// page shows the base workflow), with the three themes, and the script is +// loaded from a file, touches no network and keeps nothing in storage. +func TestInstallSectionAndScript(t *testing.T) { + dir := buildDir(t) + page := readBuilt(t, dir, "index.html") + for _, want := range []string{ + `