From 348f0f6432594ecb7612e8c82b0dbc53d3a0cd12 Mon Sep 17 00:00:00 2001 From: abhinavgautam01 Date: Tue, 1 Dec 2026 14:10:16 +0530 Subject: [PATCH 1/2] Parse rebar.config deps and plugins and OTP application metadata from *.app.src --- README.md | 29 ++- internal/rebar/appsrc.go | 100 ++++++++++ internal/rebar/appsrc_test.go | 88 +++++++++ internal/rebar/config.go | 155 +++++++++++++++ internal/rebar/config_test.go | 98 ++++++++++ internal/rebar/term.go | 346 ++++++++++++++++++++++++++++++++++ internal/rebar/term_test.go | 65 +++++++ manifests_test.go | 19 ++ rebar_manifests_test.go | 49 +++++ testdata/rebar/myapp.app.src | 22 +++ testdata/rebar/rebar.config | 36 ++++ 11 files changed, 1006 insertions(+), 1 deletion(-) create mode 100644 internal/rebar/appsrc.go create mode 100644 internal/rebar/appsrc_test.go create mode 100644 internal/rebar/config.go create mode 100644 internal/rebar/config_test.go create mode 100644 internal/rebar/term.go create mode 100644 internal/rebar/term_test.go create mode 100644 rebar_manifests_test.go create mode 100644 testdata/rebar/myapp.app.src create mode 100644 testdata/rebar/rebar.config diff --git a/README.md b/README.md index 22bad37..ef0d247 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,7 @@ func main() { | hackage | *.cabal, stack.yaml, cabal.project | stack.yaml.lock, cabal.config, cabal.project.freeze | | haxelib | haxelib.json | | | helm | Chart.yaml, requirements.yaml | Chart.lock, requirements.lock | -| hex | mix.exs, gleam.toml | mix.lock, rebar.lock | +| hex | mix.exs, gleam.toml, rebar.config, *.app.src | mix.lock, rebar.lock | | ips | *.p5m | | | julia | Project.toml, REQUIRE | Manifest.toml | | lean | lakefile.toml, lakefile.lean | lake-manifest.json | @@ -124,6 +124,31 @@ and `source` constraints carry no version and are skipped. Entries inside `if`, `elif` and `else` blocks keep the condition in `Marker`, for example `!(os(windows)) && impl(ghc >= 9.6)`, without evaluating it. +### Erlang output + +`rebar.config` and `*.app.src` are read as Erlang terms, the way +`file:consult/1` reads them, so comments, quoted atoms, binaries and maps are +handled. A file that is not valid term syntax, such as one using macros, is a +parse error. + +`rebar.config` reports top-level `deps` with runtime scope under a +`deps/` location. `deps` inside `profiles` use test scope for the `test` +profile, runtime scope for `prod` and development scope for any other profile. +`plugins` and `project_plugins` use build scope wherever they appear. A version +string is kept as written, such as `"~> 3.9"`. `{App, {pkg, Name}}` reports the +Hex package `Name` while the location keeps `App`. Git sources keep a `branch`, +`tag` or `ref` in `Branch`, `Tag` or `Ref`, while `git_subdir` keeps its +directory in `Rel`. Other version control sources use the `url` kind. A rebar2 +version regex next to a source, such as `".*"`, is not a version and is dropped. + +`*.app.src` sets `Name` and `Version` from the application name and `vsn`, as +well as `Licenses` from `licenses`. A `vsn` of `git` or a command tuple is not +a version, so it is left empty. Entries in `applications` and +`included_applications` are runtime dependencies without versions, while those +in `optional_applications` have optional scope. Applications that ship with +Erlang/OTP or Elixir, such as `kernel`, `stdlib` and `logger`, are not packages, +so they are skipped. + ### vcpkg CONTROL output Classic vcpkg ports declare their dependencies in `ports//CONTROL`. The @@ -601,6 +626,8 @@ unexpected type is treated as absent rather than failing the parse. `.nuspec` fills `Summary` and `Description` verbatim, `Keywords` from `tags` split on white space, `Homepage` from `projectUrl` plus `Readme` from `readme`, with the `repository` URL, `licenseUrl` and `iconUrl` as `Links`. +`*.app.src` fills `Description` from `description`, with each `links` entry as +a `Links` item under its own label. ### Registry diff --git a/internal/rebar/appsrc.go b/internal/rebar/appsrc.go new file mode 100644 index 0000000..448f338 --- /dev/null +++ b/internal/rebar/appsrc.go @@ -0,0 +1,100 @@ +package rebar + +import ( + "github.com/git-pkgs/manifests/internal/core" +) + +func init() { + core.Register("hex", core.Manifest, &appSrcParser{}, core.SuffixMatch(".app.src")) +} + +// appSrcParser parses OTP application resource files (*.app.src). +type appSrcParser struct{} + +// otpApplications ships with Erlang/OTP or Elixir, so it is not a package. +var otpApplications = map[string]bool{ + "asn1": true, "common_test": true, "compiler": true, "crypto": true, "debugger": true, + "dialyzer": true, "diameter": true, "edoc": true, "eldap": true, "erl_docgen": true, + "erl_interface": true, "erts": true, "et": true, "eunit": true, "ftp": true, + "hipe": true, "inets": true, "jinterface": true, "kernel": true, "megaco": true, + "mnesia": true, "observer": true, "odbc": true, "os_mon": true, "otp_mibs": true, + "parsetools": true, "public_key": true, "reltool": true, "runtime_tools": true, + "sasl": true, "snmp": true, "ssh": true, "ssl": true, "stdlib": true, + "syntax_tools": true, "tftp": true, "tools": true, "wx": true, "xmerl": true, + "elixir": true, "eex": true, "ex_unit": true, "iex": true, "logger": true, "mix": true, +} + +func (p *appSrcParser) Parse(filename string, content []byte) (*core.Result, error) { + terms, err := parseErlangTerms(string(content)) + if err != nil { + return nil, &core.ParseError{Filename: filename, Err: err} + } + result := &core.Result{} + if len(terms) == 0 { + return result, nil + } + application, ok := terms[0].tagged("application") + if !ok || len(application) != 2 || application[0].kind != termAtom { + return result, nil + } + result.Name = application[0].value + properties := application[1] + + if vsn, ok := property(properties, "vsn"); ok && vsn.kind == termString && vsn.value != "git" { + result.Version = vsn.value + } + if description, ok := property(properties, "description"); ok && description.kind == termString { + value := description.value + result.Metadata.Description = &value + } + if licenses, ok := property(properties, "licenses"); ok { + for _, license := range licenses.items { + if license.kind == termString && license.value != "" { + result.Licenses = append(result.Licenses, license.value) + } + } + } + if links, ok := property(properties, "links"); ok { + for _, link := range links.items { + if link.kind == termTuple && len(link.items) == 2 && link.items[0].kind == termString && link.items[1].kind == termString { + result.Metadata.Links = append(result.Metadata.Links, core.Link{Label: link.items[0].value, URL: link.items[1].value}) + } + } + } + + // OTP 24 requires optional applications to also be listed in applications. + optional := make(map[string]bool) + if list, ok := property(properties, "optional_applications"); ok { + for _, app := range list.items { + if app.kind == termAtom { + optional[app.value] = true + } + } + } + locations := make(map[string]int) + seen := make(map[string]bool) + for _, field := range []string{"applications", "included_applications", "optional_applications"} { + list, ok := property(properties, field) + if !ok { + continue + } + for _, app := range list.items { + if app.kind != termAtom || otpApplications[app.value] || seen[app.value] { + continue + } + seen[app.value] = true + scope := core.Runtime + if optional[app.value] { + scope = core.Optional + } + result.Dependencies = append(result.Dependencies, core.Dependency{Name: app.value, Scope: scope, Direct: true}) + result.Declarations = append(result.Declarations, core.Declaration{ + Name: app.value, + Scope: scope, + Direct: true, + Location: core.NextLocation(locations, field+"/"+app.value), + }) + } + } + return result, nil +} diff --git a/internal/rebar/appsrc_test.go b/internal/rebar/appsrc_test.go new file mode 100644 index 0000000..9d24b6e --- /dev/null +++ b/internal/rebar/appsrc_test.go @@ -0,0 +1,88 @@ +package rebar + +import ( + "os" + "reflect" + "testing" + + "github.com/git-pkgs/manifests/internal/core" +) + +func TestAppSrc(t *testing.T) { + content, err := os.ReadFile("../../testdata/rebar/myapp.app.src") + if err != nil { + t.Fatalf("failed to read fixture: %v", err) + } + res, err := (&appSrcParser{}).Parse("myapp.app.src", content) + if err != nil { + t.Fatalf("Parse failed: %v", err) + } + + if res.Name != "myapp" || res.Version != "0.3.1" { + t.Errorf("package = %q %q", res.Name, res.Version) + } + if !reflect.DeepEqual(res.Licenses, []string{"Apache-2.0", "MIT"}) { + t.Errorf("licenses = %v", res.Licenses) + } + if res.Metadata.Description == nil || *res.Metadata.Description != "An example OTP application" { + t.Errorf("description = %v", res.Metadata.Description) + } + wantLinks := []core.Link{ + {Label: "GitHub", URL: "https://github.com/example/myapp"}, + {Label: "Changelog", URL: "https://github.com/example/myapp/blob/main/CHANGELOG.md"}, + } + if !reflect.DeepEqual(res.Metadata.Links, wantLinks) { + t.Errorf("links = %+v", res.Metadata.Links) + } + + want := []core.Dependency{ + {Name: "cowboy", Scope: core.Runtime, Direct: true}, + {Name: "jsx", Scope: core.Runtime, Direct: true}, + {Name: "telemetry", Scope: core.Optional, Direct: true}, + {Name: "worker_pool", Scope: core.Runtime, Direct: true}, + } + if !reflect.DeepEqual(res.Dependencies, want) { + t.Errorf("dependencies = %+v", res.Dependencies) + } + var locations []string + for _, declaration := range res.Declarations { + locations = append(locations, declaration.Location) + } + wantLocations := []string{"applications/cowboy", "applications/jsx", "applications/telemetry", "included_applications/worker_pool"} + if !reflect.DeepEqual(locations, wantLocations) { + t.Errorf("locations = %v", locations) + } +} + +func TestAppSrcEdgeCases(t *testing.T) { + tests := []struct { + name string + content string + app string + version string + deps int + }{ + {"git version", `{application, a, [{vsn, "git"}, {applications, [kernel, stdlib, logger, elixir]}]}.`, "a", "", 0}, + {"command version", `{application, b, [{vsn, {cmd, "echo 1"}}, {applications, [dep]}]}.`, "b", "", 1}, + {"only optional", `{application, c, [{optional_applications, [opt]}]}.`, "c", "", 1}, + {"not an application", `{other, d, []}.`, "", "", 0}, + {"empty", "% nothing here\n", "", "", 0}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + res, err := (&appSrcParser{}).Parse("x.app.src", []byte(tt.content)) + if err != nil { + t.Fatal(err) + } + if res.Name != tt.app || res.Version != tt.version || len(res.Dependencies) != tt.deps { + t.Errorf("result = %q %q %+v", res.Name, res.Version, res.Dependencies) + } + }) + } +} + +func TestAppSrcInvalid(t *testing.T) { + if _, err := (&appSrcParser{}).Parse("x.app.src", []byte("{application, a, [")); err == nil { + t.Error("expected a parse error") + } +} diff --git a/internal/rebar/config.go b/internal/rebar/config.go new file mode 100644 index 0000000..b14007f --- /dev/null +++ b/internal/rebar/config.go @@ -0,0 +1,155 @@ +package rebar + +import ( + "github.com/git-pkgs/manifests/internal/core" +) + +func init() { + core.Register("hex", core.Manifest, &rebarConfigParser{}, core.ExactMatch("rebar.config")) +} + +// rebarConfigParser parses the deps and plugins of rebar.config files. +type rebarConfigParser struct{} + +type rebarConfigWalker struct { + result *core.Result + locations map[string]int +} + +func (p *rebarConfigParser) Parse(filename string, content []byte) (*core.Result, error) { + terms, err := parseErlangTerms(string(content)) + if err != nil { + return nil, &core.ParseError{Filename: filename, Err: err} + } + walker := &rebarConfigWalker{result: &core.Result{}, locations: make(map[string]int)} + walker.options(terms, "", core.Runtime) + return walker.result, nil +} + +// options reads deps, plugins and profiles from a list of config entries. +func (w *rebarConfigWalker) options(entries []erlTerm, prefix string, scope core.Scope) { + for _, entry := range entries { + if entry.kind != termTuple || len(entry.items) != 2 || entry.items[0].kind != termAtom { + continue + } + key, value := entry.items[0].value, entry.items[1] + switch key { + case "deps": + w.deps(value, prefix+"deps", scope) + case "plugins", "project_plugins": + w.deps(value, prefix+key, core.Build) + case "profiles": + if prefix != "" || value.kind != termList { + continue + } + for _, profile := range value.items { + if profile.kind != termTuple || len(profile.items) != 2 || profile.items[0].kind != termAtom || profile.items[1].kind != termList { + continue + } + name := profile.items[0].value + w.options(profile.items[1].items, "profiles/"+name+"/", profileScope(name)) + } + } + } +} + +func profileScope(profile string) core.Scope { + switch profile { + case "test": + return core.Test + case "prod": + return core.Runtime + } + return core.Development +} + +func (w *rebarConfigWalker) deps(list erlTerm, prefix string, scope core.Scope) { + if list.kind != termList { + return + } + for _, entry := range list.items { + app, dep, ok := rebarDependency(entry) + if !ok { + continue + } + dep.Scope = scope + dep.Direct = true + w.result.Dependencies = append(w.result.Dependencies, dep) + w.result.Declarations = append(w.result.Declarations, core.Declaration{ + Name: dep.Name, + Version: dep.Version, + Scope: dep.Scope, + Direct: true, + Location: core.NextLocation(w.locations, prefix+"/"+app), + Source: dep.Source, + }) + } +} + +// rebarDependency reads a deps entry and returns its application name. +func rebarDependency(entry erlTerm) (string, core.Dependency, bool) { + if entry.kind == termAtom { + return entry.value, core.Dependency{Name: entry.value}, true + } + if entry.kind != termTuple || len(entry.items) < 2 || entry.items[0].kind != termAtom { + return "", core.Dependency{}, false + } + app := entry.items[0].value + dep := core.Dependency{Name: app} + rest := entry.items[1:] + if rest[0].kind == termString { + dep.Version = rest[0].value + rest = rest[1:] + } + if len(rest) == 0 { + return app, dep, true + } + if pkg, ok := rest[0].tagged("pkg"); ok { + // {pkg, Name} installs the Hex package Name under the app name. + if len(pkg) == 0 || pkg[0].kind != termAtom { + return "", core.Dependency{}, false + } + dep.Name = pkg[0].value + return app, dep, true + } + source, ok := rebarSource(rest[0]) + if !ok { + return "", core.Dependency{}, false + } + // A version next to a source is a rebar2 regex such as ".*", not a version. + dep.Version = "" + dep.Source = source + return app, dep, true +} + +// rebarSource reads {git, URL, Spec}, {git_subdir, URL, Spec, Dir} or {hg, URL, Spec}. +func rebarSource(term erlTerm) (core.Source, bool) { + if term.kind != termTuple || len(term.items) < 2 || term.items[0].kind != termAtom || term.items[1].kind != termString { + return core.Source{}, false + } + kind := term.items[0].value + source := core.Source{Kind: core.SourceURL, Value: term.items[1].value} + if kind == "git" || kind == "git_subdir" { + source.Kind = core.SourceGit + } + if len(term.items) > 2 { + spec := term.items[2] + switch { + case spec.kind == termString: + source.Ref = spec.value + case spec.kind == termTuple && len(spec.items) == 2 && spec.items[1].kind == termString: + switch { + case spec.items[0].isAtom("branch"): + source.Branch = spec.items[1].value + case spec.items[0].isAtom("tag"): + source.Tag = spec.items[1].value + case spec.items[0].isAtom("ref"): + source.Ref = spec.items[1].value + } + } + } + if kind == "git_subdir" && len(term.items) > 3 && term.items[3].kind == termString { + source.Rel = term.items[3].value + } + return source, true +} diff --git a/internal/rebar/config_test.go b/internal/rebar/config_test.go new file mode 100644 index 0000000..c53508d --- /dev/null +++ b/internal/rebar/config_test.go @@ -0,0 +1,98 @@ +package rebar + +import ( + "os" + "reflect" + "testing" + + "github.com/git-pkgs/manifests/internal/core" +) + +func TestRebarConfig(t *testing.T) { + content, err := os.ReadFile("../../testdata/rebar/rebar.config") + if err != nil { + t.Fatalf("failed to read fixture: %v", err) + } + res, err := (&rebarConfigParser{}).Parse("rebar.config", content) + if err != nil { + t.Fatalf("Parse failed: %v", err) + } + + runtime := func(name, version string, source core.Source) core.Dependency { + return core.Dependency{Name: name, Version: version, Scope: core.Runtime, Direct: true, Source: source} + } + git := func(url string) core.Source { return core.Source{Kind: core.SourceGit, Value: url} } + recon := git("https://github.com/ferd/recon.git") + recon.Tag = "2.5.3" + hackney := git("https://github.com/benoitc/hackney.git") + hackney.Branch = "master" + meck := git("git://github.com/eproxus/meck.git") + meck.Ref = "a1b2c3d" + rebarMix := git("https://github.com/tsloughter/rebar3_tools.git") + rebarMix.Branch, rebarMix.Rel = "main", "rebar_mix" + legacy := git("https://github.com/example/legacy.git") + legacy.Ref = "HEAD" + + want := []core.Dependency{ + runtime("jsx", "", core.Source{}), + runtime("cowboy", "2.10.0", core.Source{}), + runtime("lager", "~> 3.9", core.Source{}), + runtime("jiffy_fork", "1.1.1", core.Source{}), + runtime("gproc_ng", "", core.Source{}), + runtime("recon", "", recon), + runtime("hackney", "", hackney), + runtime("meck", "", meck), + runtime("rebar_mix", "", rebarMix), + runtime("legacy", "", legacy), + runtime("hgdep", "", core.Source{Kind: core.SourceURL, Value: "https://hg.example.com/hgdep", Tag: "1.0"}), + {Name: "rebar3_format", Scope: core.Build, Direct: true}, + {Name: "rebar3_hex", Version: "7.0.7", Scope: core.Build, Direct: true}, + {Name: "rebar3_proper", Version: "0.12.1", Scope: core.Build, Direct: true}, + {Name: "proper", Version: "1.4.0", Scope: core.Test, Direct: true}, + {Name: "meck", Scope: core.Test, Direct: true}, + {Name: "covertool", Scope: core.Build, Direct: true}, + {Name: "edown", Version: "0.8.4", Scope: core.Development, Direct: true}, + } + if !reflect.DeepEqual(res.Dependencies, want) { + t.Errorf("dependencies = %+v", res.Dependencies) + } + + wantLocations := map[int]string{ + 0: "deps/jsx", + 3: "deps/jiffy", + 4: "deps/gproc", + 11: "project_plugins/rebar3_format", + 13: "plugins/rebar3_proper", + 15: "profiles/test/deps/meck", + 16: "profiles/test/plugins/covertool", + 17: "profiles/docs/deps/edown", + } + if len(res.Declarations) != len(want) { + t.Fatalf("declarations = %+v", res.Declarations) + } + for index, location := range wantLocations { + if got := res.Declarations[index].Location; got != location { + t.Errorf("declaration %d location = %q, want %q", index, got, location) + } + } +} + +func TestRebarConfigSkipsMalformedEntries(t *testing.T) { + content := `{deps, [ok, "string", {}, {"name", "1.0"}, {bad, {pkg}}, {bad, {git, url}}, {bad, {unknown}}]}. +{deps, not_a_list}. +{profiles, [{test, not_a_list}, bare, {test, [{profiles, [{nested, [{deps, [nested]}]}]}]}]}.` + res, err := (&rebarConfigParser{}).Parse("rebar.config", []byte(content)) + if err != nil { + t.Fatal(err) + } + want := []core.Dependency{{Name: "ok", Scope: core.Runtime, Direct: true}} + if !reflect.DeepEqual(res.Dependencies, want) { + t.Errorf("dependencies = %+v", res.Dependencies) + } +} + +func TestRebarConfigInvalid(t *testing.T) { + if _, err := (&rebarConfigParser{}).Parse("rebar.config", []byte("{deps, [jsx]}")); err == nil { + t.Error("expected a parse error") + } +} diff --git a/internal/rebar/term.go b/internal/rebar/term.go new file mode 100644 index 0000000..e1dd7f2 --- /dev/null +++ b/internal/rebar/term.go @@ -0,0 +1,346 @@ +package rebar + +import ( + "fmt" + "strings" +) + +type termKind int + +const ( + termAtom termKind = iota + termString + termNumber + termTuple + termList + termMap +) + +// erlTerm is an Erlang term; a map holds alternating keys and values. +type erlTerm struct { + kind termKind + value string + items []erlTerm +} + +func (t erlTerm) isAtom(name string) bool { return t.kind == termAtom && t.value == name } + +// tagged returns the elements of a tuple whose first element is the atom tag. +func (t erlTerm) tagged(tag string) ([]erlTerm, bool) { + if t.kind != termTuple || len(t.items) == 0 || !t.items[0].isAtom(tag) { + return nil, false + } + return t.items[1:], true +} + +// property returns the value of {key, Value} in a proplist. +func property(list erlTerm, key string) (erlTerm, bool) { + if list.kind != termList { + return erlTerm{}, false + } + for _, item := range list.items { + if rest, ok := item.tagged(key); ok && len(rest) == 1 { + return rest[0], true + } + } + return erlTerm{}, false +} + +// parseErlangTerms reads dot-terminated terms, as file:consult/1 does. +func parseErlangTerms(src string) ([]erlTerm, error) { + reader := &termReader{src: src} + var terms []erlTerm + for { + reader.skipSpace() + if reader.eof() { + return terms, nil + } + term, err := reader.term() + if err != nil { + return nil, err + } + reader.skipSpace() + if reader.eof() || reader.src[reader.pos] != '.' { + return nil, reader.errorf("expected '.' after term") + } + reader.pos++ + terms = append(terms, term) + } +} + +type termReader struct { + src string + pos int +} + +func (r *termReader) eof() bool { return r.pos >= len(r.src) } + +func (r *termReader) errorf(format string, args ...any) error { + line := strings.Count(r.src[:min(r.pos, len(r.src))], "\n") + 1 + return fmt.Errorf("line %d: %s", line, fmt.Sprintf(format, args...)) +} + +func (r *termReader) skipSpace() { + for !r.eof() { + switch r.src[r.pos] { + case '%': + for !r.eof() && r.src[r.pos] != '\n' { + r.pos++ + } + case ' ', '\t', '\n', '\r': + r.pos++ + default: + return + } + } +} + +func (r *termReader) consume(token string) bool { + r.skipSpace() + if strings.HasPrefix(r.src[r.pos:], token) { + r.pos += len(token) + return true + } + return false +} + +func (r *termReader) term() (erlTerm, error) { + r.skipSpace() + if r.eof() { + return erlTerm{}, r.errorf("unexpected end of input") + } + switch c := r.src[r.pos]; { + case c == '{': + r.pos++ + items, err := r.sequence("}") + return erlTerm{kind: termTuple, items: items}, err + case c == '[': + r.pos++ + return r.list() + case c == '"': + return r.strings() + case c == '\'': + value, err := r.quoted('\'') + return erlTerm{kind: termAtom, value: value}, err + case strings.HasPrefix(r.src[r.pos:], "<<"): + r.pos += 2 + return r.binary() + case strings.HasPrefix(r.src[r.pos:], "#{"): + r.pos += 2 + return r.mapTerm() + case c == '$': + return r.char() + case c == '-' || isDigit(c): + return r.number(), nil + case isAtomStart(c): + start := r.pos + for !r.eof() && isAtomChar(r.src[r.pos]) { + r.pos++ + } + return erlTerm{kind: termAtom, value: r.src[start:r.pos]}, nil + } + return erlTerm{}, r.errorf("unexpected character %q", r.src[r.pos]) +} + +// sequence reads comma separated terms up to the closing token. +func (r *termReader) sequence(closing string) ([]erlTerm, error) { + var items []erlTerm + if r.consume(closing) { + return items, nil + } + for { + item, err := r.term() + if err != nil { + return nil, err + } + items = append(items, item) + if r.consume(closing) { + return items, nil + } + if !r.consume(",") { + return nil, r.errorf("expected ',' or %q", closing) + } + } +} + +func (r *termReader) list() (erlTerm, error) { + list := erlTerm{kind: termList} + if r.consume("]") { + return list, nil + } + for { + item, err := r.term() + if err != nil { + return list, err + } + list.items = append(list.items, item) + switch { + case r.consume("]"): + return list, nil + case r.consume("|"): + tail, err := r.term() + if err != nil { + return list, err + } + if tail.kind == termList { + list.items = append(list.items, tail.items...) + } + if !r.consume("]") { + return list, r.errorf("expected ']' after list tail") + } + return list, nil + case !r.consume(","): + return list, r.errorf("expected ',' or ']'") + } + } +} + +// strings reads a string literal and any literals adjacent to it. +func (r *termReader) strings() (erlTerm, error) { + var value strings.Builder + for { + part, err := r.quoted('"') + if err != nil { + return erlTerm{}, err + } + value.WriteString(part) + r.skipSpace() + if r.eof() || r.src[r.pos] != '"' { + return erlTerm{kind: termString, value: value.String()}, nil + } + } +} + +func (r *termReader) quoted(quote byte) (string, error) { + r.pos++ + var value strings.Builder + for !r.eof() { + c := r.src[r.pos] + r.pos++ + switch { + case c == quote: + return value.String(), nil + case c == '\\' && !r.eof(): + value.WriteByte(unescape(r.src[r.pos])) + r.pos++ + default: + value.WriteByte(c) + } + } + return "", r.errorf("unterminated quoted text") +} + +// binary reads <<...>>, keeping only the text of its string segments. +func (r *termReader) binary() (erlTerm, error) { + binary := erlTerm{kind: termString} + if r.consume(">>") { + return binary, nil + } + for { + segment, err := r.term() + if err != nil { + return binary, err + } + if segment.kind == termString { + binary.value += segment.value + } + if r.consume(":") { + if _, err := r.term(); err != nil { + return binary, err + } + } + if r.consume("/") { + for !r.eof() && (isAtomChar(r.src[r.pos]) || r.src[r.pos] == '-') { + r.pos++ + } + } + if r.consume(">>") { + return binary, nil + } + if !r.consume(",") { + return binary, r.errorf("expected ',' or '>>'") + } + } +} + +func (r *termReader) mapTerm() (erlTerm, error) { + result := erlTerm{kind: termMap} + if r.consume("}") { + return result, nil + } + for { + key, err := r.term() + if err != nil { + return result, err + } + if !r.consume("=>") && !r.consume(":=") { + return result, r.errorf("expected '=>' in map") + } + value, err := r.term() + if err != nil { + return result, err + } + result.items = append(result.items, key, value) + if r.consume("}") { + return result, nil + } + if !r.consume(",") { + return result, r.errorf("expected ',' or '}'") + } + } +} + +func (r *termReader) char() (erlTerm, error) { + r.pos++ + if r.eof() { + return erlTerm{}, r.errorf("unexpected end of input") + } + c := r.src[r.pos] + r.pos++ + if c == '\\' && !r.eof() { + c = unescape(r.src[r.pos]) + r.pos++ + } + return erlTerm{kind: termNumber, value: string(c)}, nil +} + +// number reads integers, floats and based integers such as 16#ff. +func (r *termReader) number() erlTerm { + start := r.pos + if r.src[r.pos] == '-' { + r.pos++ + } + for !r.eof() && (isAtomChar(r.src[r.pos]) || r.src[r.pos] == '#') { + r.pos++ + } + if r.pos+1 < len(r.src) && r.src[r.pos] == '.' && isDigit(r.src[r.pos+1]) { + r.pos++ + for !r.eof() { + c := r.src[r.pos] + exponentSign := (c == '+' || c == '-') && (r.src[r.pos-1] == 'e' || r.src[r.pos-1] == 'E') + if !isAtomChar(c) && !exponentSign { + break + } + r.pos++ + } + } + return erlTerm{kind: termNumber, value: r.src[start:r.pos]} +} + +func unescape(c byte) byte { + switch c { + case 'n': + return '\n' + case 't': + return '\t' + case 'r': + return '\r' + case 's': + return ' ' + } + return c +} + +func isDigit(c byte) bool { return c >= '0' && c <= '9' } +func isAtomStart(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_' } +func isAtomChar(c byte) bool { return isAtomStart(c) || isDigit(c) || c == '@' } diff --git a/internal/rebar/term_test.go b/internal/rebar/term_test.go new file mode 100644 index 0000000..35f2da1 --- /dev/null +++ b/internal/rebar/term_test.go @@ -0,0 +1,65 @@ +package rebar + +import ( + "reflect" + "testing" +) + +func TestParseErlangTerms(t *testing.T) { + src := `%% comment +{a, 'quoted atom', "str" " joined", <<"bin", "ary"/utf8>>, <<>>, $x, $\n}. +[1, -2, 3.5e-2, 16#ff, 1_000 | [tail]]. % trailing comment +#{key => [x], <<"k">> := "v"}. +"esc\"aped\tvalue". +` + terms, err := parseErlangTerms(src) + if err != nil { + t.Fatal(err) + } + atom := func(v string) erlTerm { return erlTerm{kind: termAtom, value: v} } + str := func(v string) erlTerm { return erlTerm{kind: termString, value: v} } + num := func(v string) erlTerm { return erlTerm{kind: termNumber, value: v} } + want := []erlTerm{ + {kind: termTuple, items: []erlTerm{ + atom("a"), atom("quoted atom"), str("str joined"), str("binary"), str(""), num("x"), num("\n"), + }}, + {kind: termList, items: []erlTerm{num("1"), num("-2"), num("3.5e-2"), num("16#ff"), num("1_000"), atom("tail")}}, + {kind: termMap, items: []erlTerm{atom("key"), {kind: termList, items: []erlTerm{atom("x")}}, str("k"), str("v")}}, + str("esc\"aped\tvalue"), + } + if !reflect.DeepEqual(terms, want) { + t.Errorf("terms = %+v", terms) + } +} + +func TestParseErlangTermsErrors(t *testing.T) { + for _, src := range []string{ + "{a, b}", + "{a, b", + "[a b].", + `"unterminated.`, + "#{a}.", + "<<1 2>>.", + "{a, ?MACRO}.", + } { + if _, err := parseErlangTerms(src); err == nil { + t.Errorf("parseErlangTerms(%q) succeeded", src) + } + } +} + +func TestProperty(t *testing.T) { + terms, err := parseErlangTerms(`[{vsn, "1.0"}, {vsn, "a", "b"}, other].`) + if err != nil { + t.Fatal(err) + } + if value, ok := property(terms[0], "vsn"); !ok || value.value != "1.0" { + t.Errorf("property = %+v, %v", value, ok) + } + if _, ok := property(terms[0], "missing"); ok { + t.Error("missing property found") + } + if _, ok := property(erlTerm{kind: termAtom}, "vsn"); ok { + t.Error("property of a non-list found") + } +} diff --git a/manifests_test.go b/manifests_test.go index c08e888..9594de1 100644 --- a/manifests_test.go +++ b/manifests_test.go @@ -43,6 +43,8 @@ func TestParseAllEcosystems(t *testing.T) { {"nix flake.lock", "testdata/nix/flake.lock", "nix", Lockfile}, {"vagrant Vagrantfile", "testdata/vagrant/Vagrantfile", "vagrant", Manifest}, {"hackage stack.yaml", "testdata/hackage/stack.yaml", "hackage", Manifest}, + {"hex rebar.config", "testdata/rebar/rebar.config", "hex", Manifest}, + {"hex myapp.app.src", "testdata/rebar/myapp.app.src", "hex", Manifest}, {"hackage cabal.project", "testdata/hackage/cabal.project", "hackage", Manifest}, } @@ -404,6 +406,12 @@ func TestParseDeclaredLicenses(t *testing.T) { content: `{"license":{"type":"ISC","url":"https://example.test/ISC"},"licenses":[{"type":"MIT"},{"type":"Apache-2.0"}]}`, licenses: []string{"ISC", "MIT", "Apache-2.0"}, }, + { + name: "app.src", + filename: "example.app.src", + content: `{application, example, [{vsn, "1.0.0"}, {licenses, ["Apache-2.0"]}]}.`, + licenses: []string{"Apache-2.0"}, + }, { name: "cargo", filename: "Cargo.toml", @@ -593,6 +601,7 @@ func TestParseName(t *testing.T) { {"testdata/dub/dub.json", "ddox", "-"}, {"testdata/haxelib/haxelib.json", "flixel", "-"}, {"testdata/vcpkg/vcpkg.json", "warzone2100", "-"}, + {"testdata/rebar/myapp.app.src", "myapp", "0.3.1"}, {"testdata/cpan/META.json", "App-rainbarf", "-"}, {"testdata/cran/DESCRIPTION", "ggplot2", "-"}, {"testdata/hackage/example.cabal", "cabal-parser", "-"}, @@ -705,6 +714,16 @@ func TestIdentifyFiles(t *testing.T) { {"pyproject.toml", "pypi", Manifest, true}, {"poetry.lock", "pypi", Lockfile, true}, + // hex + {"mix.exs", "hex", Manifest, true}, + {"mix.lock", "hex", Lockfile, true}, + {"rebar.lock", "hex", Lockfile, true}, + {"rebar.config", "hex", Manifest, true}, + {"myapp.app.src", "hex", Manifest, true}, + {"src/myapp.app.src", "hex", Manifest, true}, + {"rebar.config.script", "", "", false}, + {"myapp.app", "", "", false}, + // hackage {"example.cabal", "hackage", Manifest, true}, {"stack.yaml", "hackage", Manifest, true}, diff --git a/rebar_manifests_test.go b/rebar_manifests_test.go new file mode 100644 index 0000000..7da1d66 --- /dev/null +++ b/rebar_manifests_test.go @@ -0,0 +1,49 @@ +package manifests + +import ( + "os" + "testing" +) + +func TestRebarConfigParse(t *testing.T) { + content, err := os.ReadFile("testdata/rebar/rebar.config") + if err != nil { + t.Fatal(err) + } + got, err := Parse("rebar.config", content) + if err != nil { + t.Fatal(err) + } + if got.Ecosystem != "hex" || got.Kind != Manifest || len(got.Dependencies) != 18 { + t.Fatalf("got %s %s with %d dependencies", got.Ecosystem, got.Kind, len(got.Dependencies)) + } + if dep := got.Dependencies[3]; dep.Name != "jiffy_fork" || dep.PURL != "pkg:hex/jiffy_fork" { + t.Errorf("renamed dependency = %+v", dep) + } + if declaration := got.Declarations[3]; declaration.Location != "deps/jiffy" || declaration.PURL != "pkg:hex/jiffy_fork" { + t.Errorf("renamed declaration = %+v", declaration) + } + if dep := got.Dependencies[5]; dep.Source.Kind != SourceGit || dep.Source.Tag != "2.5.3" { + t.Errorf("git dependency = %+v", dep) + } +} + +func TestAppSrcParse(t *testing.T) { + content, err := os.ReadFile("testdata/rebar/myapp.app.src") + if err != nil { + t.Fatal(err) + } + got, err := Parse("src/myapp.app.src", content) + if err != nil { + t.Fatal(err) + } + if got.Ecosystem != "hex" || got.Kind != Manifest || got.Name != "myapp" || len(got.Dependencies) != 4 { + t.Fatalf("got %s %s %q with %d dependencies", got.Ecosystem, got.Kind, got.Name, len(got.Dependencies)) + } + if got.Metadata.Description == nil || len(got.Metadata.Links) != 2 { + t.Errorf("metadata = %+v", got.Metadata) + } + if dep := got.Dependencies[0]; dep.Name != "cowboy" || dep.PURL != "pkg:hex/cowboy" { + t.Errorf("first dependency = %+v", dep) + } +} diff --git a/testdata/rebar/myapp.app.src b/testdata/rebar/myapp.app.src new file mode 100644 index 0000000..6fa82f4 --- /dev/null +++ b/testdata/rebar/myapp.app.src @@ -0,0 +1,22 @@ +%% Application resource file +{application, myapp, + [{description, "An example OTP application"}, + {vsn, "0.3.1"}, + {registered, [myapp_sup]}, + {mod, {myapp_app, []}}, + {applications, + [kernel, + stdlib, + crypto, + cowboy, + jsx, + telemetry + ]}, + {included_applications, [worker_pool]}, + {optional_applications, [telemetry]}, + {env, [{port, 8080}, {name, <<"myapp">>}]}, + {modules, []}, + {licenses, ["Apache-2.0", "MIT"]}, + {links, [{"GitHub", "https://github.com/example/myapp"}, + {"Changelog", "https://github.com/example/myapp/blob/main/CHANGELOG.md"}]} + ]}. diff --git a/testdata/rebar/rebar.config b/testdata/rebar/rebar.config new file mode 100644 index 0000000..f5bb19c --- /dev/null +++ b/testdata/rebar/rebar.config @@ -0,0 +1,36 @@ +%% -*- mode: erlang -*- +{minimum_otp_vsn, "24"}. + +{erl_opts, [debug_info, warnings_as_errors, {parse_transform, lager_transform}]}. + +{deps, [ + jsx, % latest Hex release + {cowboy, "2.10.0"}, + {lager, "~> 3.9"}, + {jiffy, "1.1.1", {pkg, jiffy_fork}}, + {gproc, {pkg, gproc_ng}}, + {recon, {git, "https://github.com/ferd/recon.git", {tag, "2.5.3"}}}, + {hackney, {git, "https://github.com/benoitc/hackney.git", {branch, "master"}}}, + {meck, {git, "git://github.com/eproxus/meck.git", {ref, "a1b2c3d"}}}, + {rebar_mix, {git_subdir, "https://github.com/tsloughter/rebar3_tools.git", {branch, "main"}, "rebar_mix"}}, + {legacy, ".*", {git, "https://github.com/example/legacy.git", "HEAD"}}, + {hgdep, {hg, "https://hg.example.com/hgdep", {tag, "1.0"}}} +]}. + +{project_plugins, [rebar3_format, {rebar3_hex, "7.0.7"}]}. +{plugins, [{rebar3_proper, "0.12.1"}]}. + +{relx, [{release, {myapp, "0.1.0"}, [myapp, sasl]}, {dev_mode, true}]}. + +{shell, [{config, "config/sys.config"}, {apps, [myapp]}]}. + +{profiles, [ + {test, [ + {deps, [{proper, "1.4.0"}, meck]}, + {plugins, [covertool]} + ]}, + {docs, [{deps, [{edown, "0.8.4"}]}]}, + {prod, [{relx, [{dev_mode, false}]}]} +]}. + +{hex, #{doc => #{provider => ex_doc}}}. From a17884e48fe39f250504f694146e1e2fca454829 Mon Sep 17 00:00:00 2001 From: abhinavgautam01 Date: Tue, 1 Dec 2026 15:23:45 +0530 Subject: [PATCH 2/2] Limit Erlang term nesting depth to avoid stack exhaustion --- README.md | 2 +- internal/rebar/config_test.go | 7 +++++-- internal/rebar/term.go | 13 +++++++++++-- internal/rebar/term_test.go | 20 ++++++++++++++++++++ 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ef0d247..97a82e1 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,7 @@ and `source` constraints carry no version and are skipped. Entries inside `rebar.config` and `*.app.src` are read as Erlang terms, the way `file:consult/1` reads them, so comments, quoted atoms, binaries and maps are handled. A file that is not valid term syntax, such as one using macros, is a -parse error. +parse error, as is one with terms nested more than 100 levels deep. `rebar.config` reports top-level `deps` with runtime scope under a `deps/` location. `deps` inside `profiles` use test scope for the `test` diff --git a/internal/rebar/config_test.go b/internal/rebar/config_test.go index c53508d..67c708c 100644 --- a/internal/rebar/config_test.go +++ b/internal/rebar/config_test.go @@ -3,6 +3,7 @@ package rebar import ( "os" "reflect" + "strings" "testing" "github.com/git-pkgs/manifests/internal/core" @@ -92,7 +93,9 @@ func TestRebarConfigSkipsMalformedEntries(t *testing.T) { } func TestRebarConfigInvalid(t *testing.T) { - if _, err := (&rebarConfigParser{}).Parse("rebar.config", []byte("{deps, [jsx]}")); err == nil { - t.Error("expected a parse error") + for _, content := range []string{"{deps, [jsx]}", strings.Repeat("[", 1_000_000)} { + if _, err := (&rebarConfigParser{}).Parse("rebar.config", []byte(content)); err == nil { + t.Errorf("expected a parse error for %.20q", content) + } } } diff --git a/internal/rebar/term.go b/internal/rebar/term.go index e1dd7f2..654bc67 100644 --- a/internal/rebar/term.go +++ b/internal/rebar/term.go @@ -68,9 +68,13 @@ func parseErlangTerms(src string) ([]erlTerm, error) { } } +// maxTermDepth bounds term nesting so hostile input cannot exhaust the stack. +const maxTermDepth = 100 + type termReader struct { - src string - pos int + src string + pos int + depth int } func (r *termReader) eof() bool { return r.pos >= len(r.src) } @@ -105,6 +109,11 @@ func (r *termReader) consume(token string) bool { } func (r *termReader) term() (erlTerm, error) { + r.depth++ + defer func() { r.depth-- }() + if r.depth > maxTermDepth { + return erlTerm{}, r.errorf("terms nested deeper than %d", maxTermDepth) + } r.skipSpace() if r.eof() { return erlTerm{}, r.errorf("unexpected end of input") diff --git a/internal/rebar/term_test.go b/internal/rebar/term_test.go index 35f2da1..adf60dd 100644 --- a/internal/rebar/term_test.go +++ b/internal/rebar/term_test.go @@ -2,6 +2,7 @@ package rebar import ( "reflect" + "strings" "testing" ) @@ -63,3 +64,22 @@ func TestProperty(t *testing.T) { t.Error("property of a non-list found") } } + +func TestParseErlangTermsDepthLimit(t *testing.T) { + nested := func(depth int) string { + return strings.Repeat("[", depth) + strings.Repeat("]", depth) + "." + } + if _, err := parseErlangTerms(nested(maxTermDepth)); err != nil { + t.Errorf("depth %d: %v", maxTermDepth, err) + } + for _, src := range []string{ + nested(maxTermDepth + 1), + strings.Repeat("{", 1_000_000), + "{deps, " + strings.Repeat("<<", 1_000) + ">>}.", + strings.Repeat("#{a => ", 1_000) + "b}.", + } { + if _, err := parseErlangTerms(src); err == nil || !strings.Contains(err.Error(), "nested deeper") { + t.Errorf("parseErlangTerms(%.20q...) error = %v", src, err) + } + } +}