barcodecty

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 14, 2026 License: BSD-2-Clause Imports: 20 Imported by: 0

README

barcode-cty-func

CI

A Go module providing barcode image generation as a go-cty / HCL2 function. Supports 11 barcode formats and returns PNG images as bytes objects.

Backed by github.com/boombuler/barcode.

Installation

go get github.com/tsarna/barcode-cty-func

Usage

import (
    barcodecty "github.com/tsarna/barcode-cty-func"
    "github.com/zclconf/go-cty/cty/function"
)

// Register all functions in an HCL eval context
funcs := barcodecty.GetBarcodeFunctions()
// funcs is map[string]function.Function — merge into your eval context

Functions

Function Signature Description
barcode barcode(type string, data string[, options object]) bytes Generates a barcode image as a PNG bytes object
barcode(type, data[, options])

Generates a barcode image and returns it as a bytes object with content_type = "image/png".

img = barcode("qr", "https://example.com")
# img.content_type == "image/png"
Barcode Types
type string Format Dimensions Notes
"qr" QR Code 2D Supports error_correction option
"datamatrix" Data Matrix 2D
"aztec" Aztec Code 2D
"pdf417" PDF 417 2D (stacked)
"code128" Code 128 1D Most versatile 1D format; encodes full ASCII
"code93" Code 93 1D
"code39" Code 39 1D
"codabar" Codabar 1D Numeric + limited symbols
"ean13" EAN-13 1D Exactly 12 digits (check digit appended)
"ean8" EAN-8 1D Exactly 7 digits (check digit appended)
"2of5" Interleaved 2-of-5 1D Numeric only; even number of digits required
Options

The optional third argument is an object. All fields are optional. scale and width are mutually exclusive (both control horizontal sizing). height can be used alone or combined with either scale or width.

Field Type Default Applies to Description
scale number 4 all Integer pixel multiplier applied to the barcode's natural symbol size
width number all Output image width in pixels (requires height; mutually exclusive with scale)
height number see below all Output image height in pixels
error_correction string "M" "qr" only Error correction level: "L", "M", "Q", or "H"

Sizing behaviour:

  • scale: multiplies the barcode's natural width by the given integer. For 2D codes, height is scaled equally. For 1D codes, height is set to a sensible default (see below). Every module/bar maps to exactly scale pixels wide with no interpolation artefacts.
  • height: sets an explicit pixel height. Can be combined with scale (which controls width) or used alone (with default scale = 4 for width).
  • width / height: both dimensions set explicitly. Useful when the image must fit a specific pixel budget.
  • Neither specified: defaults to scale = 4.

Default 1D barcode height:

1D barcodes have a natural height of only 1 pixel, so the function applies a default height when none is specified:

  • Code 128: 20% of the scaled width, producing a proportional barcode regardless of data length.
  • All other 1D types: scale * 24 (96px at the default scale of 4).

These defaults can always be overridden with an explicit height option.

Signature declarations

The tables above are what barcode really accepts. Its cty metadata cannot say so: the options object is optional, and the only way cty offers to make an argument optional is to make it variadic — which claims it may be repeated, when it may not — and cty has no way to describe the object's shape, so it is dynamic. Reflected from cty alone the function reads as barcode(type, data, ...options), with all four options invisible.

So externs.cty declares the real signature, as a functy //functy:extern declaration, with the options object spelled out attribute by attribute. The file is never compiled and declares nothing callable; it exists so that help(), generated documentation, and editor tooling can show what the cty metadata cannot.

Externs() returns it as opaque bytes — this package does not import functy and does not parse them:

parser.RegisterExterns(barcodecty.Externs(), barcodecty.ExternsFilename)

A host that is not a functy host can ignore it entirely; the cty Description on the function and every parameter (including the full option list) is still populated.

Examples

QR code with defaults
img = barcode("qr", "https://example.com")
QR code with high error correction and explicit scale
img = barcode("qr", "https://example.com/p?id=${ctx.payload.id}", {
    scale            = 8,
    error_correction = "H",
})
QR code at a fixed pixel size
img = barcode("qr", "https://example.com", {
    width  = 400,
    height = 400,
})
Code 128 label
label = barcode("code128", ctx.payload.tracking_number, {
    scale = 3,
})
1D barcode with explicit height
label = barcode("code39", "ITEM-42", {
    height = 80,
})
EAN-13 for retail product
# data must be exactly 12 digits; check digit is computed and appended
ean = barcode("ean13", ctx.payload.gtin12)

License

BSD 2-Clause

Documentation

Index

Constants

View Source
const ExternsFilename = "barcode-cty-func/externs.cty"

ExternsFilename is the name reported for the embedded declarations in diagnostics.

Variables

View Source
var BarcodeFunc = function.New(&function.Spec{
	Description: "Generates a barcode image as a bytes object with content_type image/png",
	Params: []function.Parameter{
		{
			Name:        "type",
			Type:        cty.String,
			Description: "Barcode symbology: \"qr\", \"datamatrix\", \"aztec\", \"pdf417\", \"code128\", \"code93\", \"code39\", \"codabar\", \"ean13\", \"ean8\", or \"2of5\"",
		},
		{
			Name:        "data",
			Type:        cty.String,
			Description: "The data to encode. What is valid depends on the symbology: EAN-13 wants 12 or 13 digits, Code 39 an uppercase alphanumeric subset, QR anything.",
		},
	},

	VarParam: &function.Parameter{
		Name:             "options",
		Type:             cty.DynamicPseudoType,
		AllowDynamicType: true,
		AllowNull:        true,
		Description: "Optional object (at most one) with any of: " +
			"scale (positive integer, default 4), " +
			"width and height (positive integers, in pixels), " +
			"error_correction (\"L\", \"M\", \"Q\" or \"H\"; QR only, default \"M\"). " +
			"scale and width are mutually exclusive, and width requires height.",
	},
	Type: func(args []cty.Value) (cty.Type, error) {
		if len(args) > 3 {
			return cty.NilType, fmt.Errorf("barcode() takes 2 or 3 arguments")
		}
		return bytescty.BytesObjectType, nil
	},
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		btype := args[0].AsString()
		data := args[1].AsString()

		var optVal cty.Value
		if len(args) > 2 {
			optVal = args[2]
		}

		opts, err := parseBarcodeOptions(optVal, btype)
		if err != nil {
			return cty.NilVal, err
		}

		return encodeBarcode(btype, data, opts)
	},
})

BarcodeFunc generates a barcode image and returns it as a bytes object with content_type "image/png". Called as barcode(type, data) or barcode(type, data, options).

Functions

func Externs added in v0.2.0

func Externs() []byte

Externs returns the functy `//functy:extern` declaration for the function GetBarcodeFunctions provides: its real signature, which its cty metadata cannot express.

The options object is *optional*, and the only way cty offers to make an argument optional is to make it variadic — which says it may be repeated, when it may not. cty also has no way to describe the object's shape, so it is declared dynamic: reflected from cty alone the function reads as `barcode(type, data, ...options)`, and what may go in that object is anybody's guess. The declaration gives it a name, a type, and its four attributes, so that help(), generated documentation, and editor tooling can show them.

The bytes are opaque to this package: it does not import functy, and nothing here parses them. A functy host registers them:

parser.RegisterExterns(barcodecty.Externs(), barcodecty.ExternsFilename)

func GetBarcodeFunctions

func GetBarcodeFunctions() map[string]function.Function

GetBarcodeFunctions returns the barcode function set for registration in a cty evaluation context.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL