Documentation
¶
Overview ¶
Package upd upgrades NPM package dependencies in package.json files while preserving formatting. It is usable both as a library and via the upd command-line tool.
The typical library flow is:
cfg := upd.DefaultConfig()
cfg.File = "package.json"
cfg.Registry = "https://registry.npmjs.org"
cfg.Timeout = 20 * time.Second
cfg.Retries = 3
cfg.Nop = true // dry-run
pkg, err := upd.ReadPackageFile(cfg.File)
if err != nil { return err }
args, err := pkg.GetUpdArgs()
if err != nil { return err }
manifest, warnings := upd.BuildManifest(pkg, args, false)
engine := upd.NewEngine(cfg)
results := engine.FetchAll(ctx, manifest.ToCheck())
updates, errs := engine.ApplyUpdates(manifest, results, pkg)
if updates > 0 && !cfg.Nop {
_ = pkg.Write(cfg.File)
}
Example ¶
Example demonstrates the library pipeline documented in doc.go against a mock registry: read package.json, build the manifest, fetch packuments, apply updates as a dry run, and inspect the result. It is executed by go test, so the flow stays compile- and behavior-verified.
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"github.com/LarsArtmann/upd"
)
func main() {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.TrimPrefix(r.URL.Path, "/") != "left-pad" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
packument := `{"name":"left-pad","dist-tags":{"latest":"2.5.0"},"versions":{"1.0.0":{},"2.5.0":{}}}`
_, _ = w.Write([]byte(packument))
}))
defer server.Close()
dir, err := os.MkdirTemp("", "upd-example")
if err != nil {
fmt.Println("mkdir:", err)
return
}
defer func() { _ = os.RemoveAll(dir) }()
file := filepath.Join(dir, "package.json")
content := []byte("{\n \"name\": \"fixture\",\n \"dependencies\": {\n \"left-pad\": \"^1.0.0\"\n }\n}\n")
if err := os.WriteFile(file, content, 0o600); err != nil {
fmt.Println("write:", err)
return
}
cfg := upd.DefaultConfig()
cfg.File = file
cfg.Registry = server.URL
cfg.Nop = true // dry-run
pkg, err := upd.ReadPackageFile(cfg.File)
if err != nil {
fmt.Println("read:", err)
return
}
manifest, _ := upd.BuildManifest(pkg, nil, false)
engine := upd.NewEngine(cfg)
results := engine.FetchAll(context.Background(), manifest.ToCheck())
updates, errCount := engine.ApplyUpdates(manifest, results, pkg)
fmt.Println(updates, errCount)
fmt.Println(manifest["left-pad"][0].State)
}
Output: 1 0 updated
Index ¶
- Constants
- Variables
- func RenderJSON(w io.Writer, manifest Manifest) error
- func ShouldDisableColor(w io.Writer) bool
- type Config
- type Engine
- type FetchResult
- type Manifest
- type Npmrc
- type PackageFile
- type Packument
- type ProgressReporter
- type RegistryClient
- type Renderer
- type RendererOptions
- type Reporter
- type Spec
- type State
Examples ¶
Constants ¶
const ( ProgramName = "upd" ProgramDesc = "Upgrade NPM Package Dependencies" ProgramURL = "https://github.com/LarsArtmann/upd" )
const ( FormatTable = "table" FormatJSON = "json" )
Output formats accepted by the --format flag.
const ( EnvQuiet = "UPD_QUIET" EnvNop = "UPD_NOP" EnvDryRun = "UPD_DRY_RUN" EnvNoColor = "UPD_NO_COLOR" EnvGreatest = "UPD_GREATEST" EnvAll = "UPD_ALL" EnvPinLatest = "UPD_PIN_LATEST" EnvJSON = "UPD_JSON" EnvFormat = "UPD_FORMAT" EnvVerbose = "UPD_VERBOSE" EnvFile = "UPD_FILE" EnvRegistry = "UPD_REGISTRY" EnvConcurrency = "UPD_CONCURRENCY" EnvRetries = "UPD_RETRIES" EnvTimeout = "UPD_TIMEOUT" )
Variables ¶
var ( ErrHelp = errors.New("help requested") ErrVersion = errors.New("version requested") )
var ( ErrFileNotFound = errorfamily.NewRejection( "file.not_found", "package configuration file not found", ) //nolint:erraudit ErrInvalidJSON = errorfamily.NewCorruption( "json.invalid", "invalid JSON in package configuration file", ) //nolint:erraudit ErrPackageNotFound = errorfamily.NewRejection( "registry.package_not_found", "package not found in NPM registry", ) "registry.unavailable", "NPM registry is unavailable", ) //nolint:erraudit ErrVersionParse = errorfamily.NewCorruption( "version.parse_failed", "failed to parse semantic version", ) //nolint:erraudit ErrNoLatestDistTag = errorfamily.NewCorruption( "version.no_latest", "no \"latest\" dist-tag found", ) //nolint:erraudit ErrNoValidVersions = errorfamily.NewCorruption( "version.no_versions", "no valid versions found", ) //nolint:erraudit ErrNoSemverVersions = errorfamily.NewCorruption( "version.no_semver", "no valid semver versions found", ) //nolint:erraudit ErrSectionNotFound = errorfamily.NewRejection( "json.section_missing", "section not found in package configuration file", ) ErrSectionNotObject = errorfamily.NewCorruption( "json.section_not_object", "section is not a JSON object", ) //nolint:erraudit ErrDependencyNotFound = errorfamily.NewRejection( "json.dependency_missing", "dependency not found in package configuration file", ) ErrConcurrentModification = errorfamily.NewConflict( "file.concurrent_modification", "package configuration file was modified concurrently since read", ) ErrPartialFailure = errorfamily.NewRejection( "update.partial_failure", "one or more dependencies could not be resolved", ) ErrInvalidFormat = errorfamily.NewRejection( "config.invalid_format", "invalid output format (use \"table\" or \"json\")", ) )
Domain errors — classified by behavioral family. Rejection = caller's fault (not found, bad input). Exit 1. Transient = temporary, retryable. Exit 75. Corruption = data damaged. Exit 65 (EX_DATAERR). Conflict = state mismatch. Exit 1.
Control-flow signals (ErrHelp, ErrVersion) live in config.go. Sentinels double as parameterized error templates via the WithContext factory idiom, which requires the concrete type; declaring them as the error interface (erraudit's suggestion) would break all 11 call sites.
var ProgramVersion = "dev"
ProgramVersion is injected at build time via -ldflags="-X github.com/LarsArtmann/upd.ProgramVersion=1.2.3".
Functions ¶
func RenderJSON ¶
RenderJSON writes machine-readable JSON to w. Intended for CI pipelines and editor integrations where the table output is difficult to parse.
func ShouldDisableColor ¶
ShouldDisableColor returns true if ANSI color codes should be suppressed. It honors the NO_COLOR environment variable (https://no-color.org/) and detects non-TTY writers (e.g. piped or redirected output).
Types ¶
type Config ¶
type Config struct {
File string
Registry string
Greatest bool
All bool
Quiet bool
Nop bool
NoColor bool
PinLatest bool
Format string
Verbose bool
Concurrency int
Retries int
Timeout time.Duration
Patterns []string
RegistryToken string
// contains filtered or unexported fields
}
func DefaultConfig ¶
func DefaultConfig() *Config
func NewCommand ¶ added in v1.2.0
NewCommand builds the root cobra command for upd. The run callback receives the signal-aware context provided by fang and the parsed configuration. The returned Config is the same instance passed to the callback, so callers can inspect it after ParseFlags in tests.
func ParseFlags ¶
ParseFlags parses CLI arguments into a Config without executing the command. It is kept for backwards compatibility and for tests. If help or version is requested, it returns ErrHelp or ErrVersion.
func (*Config) ApplyNpmrc ¶ added in v1.5.0
ApplyNpmrc merges .npmrc settings into the configuration. Explicit user configuration (--registry flag or UPD_REGISTRY) wins over file values; file values win over the built-in default.
func (*Config) EnvWarnings ¶ added in v1.5.0
EnvWarnings returns one warning per UPD_* environment variable that was set to an invalid value and ignored in favor of the built-in default.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
func (*Engine) ApplyUpdates ¶
func (e *Engine) ApplyUpdates( manifest Manifest, results map[string]*FetchResult, pkg *PackageFile, ) (int, int)
func (*Engine) WithReporter ¶
type FetchResult ¶
type FetchResult struct {
// contains filtered or unexported fields
}
FetchResult holds the outcome of fetching a single package's packument from the NPM registry. Callers receive a map of these from FetchAll and pass it opaquely to ApplyUpdates.
func (FetchResult) String ¶
func (r FetchResult) String() string
type Manifest ¶
func BuildManifest ¶
func BuildManifest(pkg *PackageFile, patterns []string, pinLatest bool) (Manifest, []string)
func (Manifest) SortedNames ¶
type Npmrc ¶ added in v1.5.0
Npmrc holds the registry settings parsed from npm configuration files. Only what upd consumes is modeled: the default registry URL and bearer tokens keyed by registry base URL. Token values are never logged, rendered, or included in errors.
func LoadNpmrc ¶ added in v1.5.0
LoadNpmrc reads .npmrc from the user's home directory and then from dir (project-local), so project-local settings win over user-level ones, mirroring npm's precedence. Missing files are not an error. The second return value carries warnings for unreadable or malformed files.
func ParseNpmrc ¶ added in v1.5.0
ParseNpmrc parses .npmrc content (INI-like "key=value" lines with ";" or "#" comments). Malformed lines are returned as warnings and skipped so a bad line cannot hide the rest of the configuration. Keys upd does not consume (scope registries, strict-ssl, ...) are ignored silently.
type PackageFile ¶
type PackageFile struct {
// contains filtered or unexported fields
}
func ReadPackageFile ¶
func ReadPackageFile(path string) (*PackageFile, error)
func (*PackageFile) GetDependencySection ¶
func (p *PackageFile) GetDependencySection(section string) (map[string]string, error)
func (*PackageFile) GetUpdArgs ¶
func (p *PackageFile) GetUpdArgs() ([]string, error)
func (*PackageFile) Raw ¶
func (p *PackageFile) Raw() []byte
func (*PackageFile) UpdateDependency ¶
func (p *PackageFile) UpdateDependency(section, name, newValue string) error
func (*PackageFile) Write ¶
func (p *PackageFile) Write(path string) error
type Packument ¶
type Packument struct {
// contains filtered or unexported fields
}
func (*Packument) GreatestVersion ¶
func (*Packument) LatestVersion ¶
func (*Packument) VersionKeys ¶
type ProgressReporter ¶
type ProgressReporter struct {
// contains filtered or unexported fields
}
func NewProgressReporter ¶
func NewProgressReporter(w io.Writer, total int, _ bool) *ProgressReporter
func (*ProgressReporter) Finish ¶
func (p *ProgressReporter) Finish()
func (*ProgressReporter) Start ¶
func (p *ProgressReporter) Start()
func (*ProgressReporter) Tick ¶
func (p *ProgressReporter) Tick(msg string, _ int)
type RegistryClient ¶
type RegistryClient struct {
// contains filtered or unexported fields
}
func NewRegistryClient ¶
func NewRegistryClient(cfg *Config) *RegistryClient
func (*RegistryClient) FetchPackument ¶
type Renderer ¶
type Renderer struct {
// contains filtered or unexported fields
}
func NewRenderer ¶
func NewRenderer(w io.Writer, opts RendererOptions) *Renderer
