ligen

package module
v0.1.0-alpha Latest Latest
Warning

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

Go to latest
Published: Sep 25, 2025 License: MIT Imports: 12 Imported by: 0

README

LIGEN

Go package for managing license files.

Features

  • Create licenses for your projects
  • Detect and identify existing license types
  • Manage copyright years and holder information
  • Parse existing license files
  • Template-based license generation
Supported Licenses
  • MIT
  • Apache 2.0
  • Mozilla Public License 2.0
  • Boost Software License 1.0
  • The Unlicense
  • GNU Lesser General Public License 3.0

Quick Start

Installation
go get github.com/MoonMoon1919/ligen
Usage

Ligen is flexible - you can define licenses and write your own file management or use service layer in the package.

Basic Usage

Create a license in just. a few lines of code:

package samples

import (
	"fmt"

	"github.com/MoonMoon1919/ligen"
)

func Basic() {
	license, err := ligen.New(
		"Example",
		"J Doe",
		2025,
		0, // End year: 0 for ongoing
		ligen.MIT,
	)
	if err != nil {
		panic(err)
	}

	writeables, err := license.Render()
	if err != nil {
		panic(err)
	}

	// Do something more interesting than print
	fmt.Print(writeables)
}

Detecting a license

Determine the type of license a repository is using:

package samples

import (
	"fmt"

	"github.com/MoonMoon1919/ligen"
)

func Detect() {
	content := `MIT License

Copyright (c) 2025 J Doe
`
	// Match takes in a threshold
	// Set intentionally very low here to avoid copying an entire license into the example
	// Package uses 0.90 when matching content loaded from file
	licenseType, err := ligen.Match(content, 0.1)
	if err != nil {
		panic(fmt.Errorf("Error: %w", err))
	}

	fmt.Printf("Detected %s", licenseType)
}

Using the service

The service handles loading files into a License and contains getters and setters:

package samples

import (
	"fmt"

	"github.com/MoonMoon1919/ligen"
)

func Service() {
	repo := ligen.FileRepository{}
	service := ligen.NewService(repo)

	// Create and write license files
	err := service.Create("My Project", "J Doe", 2024, 0, ligen.MIT)
	if err != nil {
		panic(err)
	}

	// Read license information
	years, err := service.GetYears("LICENSE")
	if err != nil {
		panic(err)
	}
	fmt.Println(years)

	licenseType, err := service.GetLicenseType("LICENSE")
	if err != nil {
		panic(err)
	}
	fmt.Println(licenseType)

	// Update license
	err = service.UpdateEndYear("LICENSE", 2025)
	if err != nil {
		panic(err)
	}
}

Contributing

See CONTRIBUTING for details.

License

MIT License - see LICENSE for details.

Disclaimers

This work does not represent the interests or technologies of any employer, past or present. It is a personal project only.

Documentation

Index

Constants

View Source
const (
	// MAX_NAME_LENGTH is the maximum amount of chars the holder of a copyright can contain
	// 128 picked arbitrarily, seemed reasonable
	MAX_NAME_LENGTH = 128
	// MAX_YEARS_PAST is the maximum amount of time in years that a copyright can be backdated
	// 50 picked arbitrarily, seemed reasonable
	MAX_YEARS_PAST = 50
)
View Source
const ApacheTemplateBody = `` /* 11392-byte string literal not displayed */

Template for Apache License 2.0

View Source
const BoostBody = `` /* 1338-byte string literal not displayed */

Body of BSL 1.0 license

View Source
const GNULesserLicenseBody = `` /* 7652-byte string literal not displayed */

Template for GNU Lesser license

View Source
const GnuLesserNoticeTemplateBody = `` /* 736-byte string literal not displayed */

Template for GNU Lesser notice

View Source
const MitTemplateBody = `` /* 1121-byte string literal not displayed */

Body of text for an MIT License

View Source
const MozillaLicenseBody = `` /* 16726-byte string literal not displayed */

Template for MPL 2.0

View Source
const SimpleNoticeTemplateBody = `{{.ProjectName}}
Copyright {{.StartYear}}{{if (gt .EndYear 0) }}-{{.EndYear}}{{end}} {{.Holder}}`

Template for notice file used for most licenses

View Source
const UnlicenseBody = `` /* 1211-byte string literal not displayed */

Body of unlicense

Variables

View Source
var (
	StartYearTooOldError        = errors.New("start year cannot be more than 50 years in the past")
	StartYearTooNewError        = errors.New("start year cannot be in the future")
	EndYearTooOldError          = errors.New("end year cannot be in the past")
	EndYearBeforeStartError     = errors.New("end year must be after start year")
	EmptyHolderError            = errors.New("holder must not be empty")
	HolderTooLongError          = errors.New("holder must be less than 128 chars")
	EmptyNameError              = errors.New("name must not be empty")
	NameTooLongError            = errors.New("name must be 128 chars")
	NameTooShortError           = errors.New("project name must have at least 1 character")
	InvalidLicenseType          = errors.New("invalid license type")
	UnsupportedLicenseTypeError = errors.New("unsupported license type")
	NoKnownTemplateError        = errors.New("no template found")
)

General use copyright line

View Source
var ApacheTemplate = template.Must(template.New("Apache").Parse(ApacheTemplateBody))
View Source
var (
	DetectionFailedError = errors.New("License detection failed")
)
View Source
var GnuLesserNoticeTemplate = template.Must(template.New("GnuLesserNotice").Parse(GnuLesserNoticeTemplateBody))
View Source
var MITTemplate = template.Must(template.New("MIT").Parse(MitTemplateBody))

Template for MIT license

View Source
var SimpleNoticeTemplate = template.Must(template.New("SimpleNotice").Parse(SimpleNoticeTemplateBody))

Functions

func DiscoverLicenseFile

func DiscoverLicenseFile() (string, error)

DiscoverLicenseFile searches the current directory for a license file and returns its path. It checks for standard license filenames in order of convention preference.

func Load

func Load(license *License, licenseLoader loader, noticeLoader loader) error

Load loads license information from the provided loaders and populates the License. The licenseLoader provides the license file content, and noticeLoader provides the NOTICE file content if required by the license type.

func ParseProjectNameFromNotice

func ParseProjectNameFromNotice(document string) (string, error)

ParseProjectNameFromNotice extracts the project name from the first line of a NOTICE file. The project name must be the entire first line, trimmed of whitespace.

func SorensonDiceCoefficient

func SorensonDiceCoefficient(left, right string) float64

SorensonDiceCoefficient calculates the similarity between two strings using bigram comparison. Returns a value between 0.0 (no similarity) and 1.0 (identical).

func Write

func Write(writer io.Writer, writeable *Writeable) error

Write writes the content of a Writeable to the provided writer.

Types

type Copyright struct {
	Holder    string
	StartYear int
	EndYear   int
}

Copyright contains copyright information used to render license notices and files.

func NewCopyright

func NewCopyright(name string, startYear int, endYear int) (Copyright, error)

NewCopyright creates a new Copyright with the given holder name and year range. The startYear must be within the last 50 years and not in the future. If endYear is 0, only startYear is set. Otherwise, endYear must be after startYear and not in the past.

func ParseCopyright

func ParseCopyright(line string) (Copyright, error)

ParseCopyright parses a copyright line and extracts the holder name and year range. Expects format: "Copyright [©|©] YYYY[-YYYY] Holder Name"

func ParseDocForCopyright

func ParseDocForCopyright(content string) (Copyright, error)

ParseDocForCopyright scans a document line by line and returns the first valid copyright it finds.

func (*Copyright) SetEndYear

func (c *Copyright) SetEndYear(year int) error

SetEndYear updates the end year of the copyright. The year must be after or equal to StartYear.

func (*Copyright) SetHolder

func (c *Copyright) SetHolder(holder string) error

SetHolder updates the copyright holder name. The holder must be non-empty and less than 128 characters.

func (*Copyright) SetStartYear

func (c *Copyright) SetStartYear(year int) error

SetStartYear updates the start year of the copyright. The year must be non-zero and not after EndYear if EndYear is set.

func (*Copyright) Validate

func (c *Copyright) Validate() error

Validate checks if the Copyright has a valid year range. Returns an error if EndYear is set and is before StartYear.

type CopyrightYears

type CopyrightYears struct {
	Start int
	End   int
}

CopyrightYears contains the start and end years of a copyright.

type FileRepository

type FileRepository struct{}

FileRepository provides filesystem-based operations for loading and writing licenses.

func (FileRepository) Load

func (f FileRepository) Load(path string, license *License) error

Load reads a license file from the specified path and populates the License. If the license type requires a NOTICE file, it will also read from a "NOTICE" file in the current directory.

func (FileRepository) Write

func (f FileRepository) Write(license *License) error

Write writes the license files to disk based on the License configuration.

type License

type License struct {
	// contains filtered or unexported fields
}

License represents a complete license configuration with project name, copyright, and license type.

func New

func New(projectName string, holder string, startYear int, endYear int, licenseType LicenseType) (*License, error)

New creates a new License with the given project name, copyright holder, year range, and license type. The project name must be 1-128 characters after trimming whitespace.

func (*License) Render

func (l *License) Render() ([]Writeable, error)

Render generates the license files for this License. Returns a slice of Writeable containing the file content and paths where they should be written.

func (*License) SetCopyrightEndYear

func (l *License) SetCopyrightEndYear(year int) error

SetCopyrightEndYear updates the copyright end year.

func (*License) SetCopyrightStartYear

func (l *License) SetCopyrightStartYear(year int) error

SetCopyrightStartYear updates the copyright start year.

func (*License) SetHolder

func (l *License) SetHolder(holder string) error

SetHolder updates the copyright holder name.

func (*License) SetLicenseType

func (l *License) SetLicenseType(licenseType LicenseType) error

SetLicenseType updates the license type.

func (*License) SetProjectName

func (l *License) SetProjectName(name string) error

SetProjectName updates the project name. The name must be 1-128 characters.

type LicenseType

type LicenseType int

LicenseType represents a supported open source license.

const (
	MIT LicenseType = iota + 1
	BOOST_1_0
	UNLICENSE
	APACHE_2_0
	MOZILLA_2_0
	GNU_LESSER_3_0
)

func AllLicensesTypes

func AllLicensesTypes() []LicenseType

AllLicensesTypes returns a slice of all supported license types.

func LicenseTypeFromString

func LicenseTypeFromString(licenseType string) (LicenseType, error)

LicenseTypeFromString parses a license type from its string representation. The input is case-insensitive.

func Match

func Match(content string, threshold float64) (LicenseType, error)

Match identifies the license type of the given content by comparing it against known license templates. The threshold parameter specifies the minimum similarity score (0.0-1.0) required for a successful match. Returns an error if no license meets the threshold or if comparison fails.

func (LicenseType) Compare

func (lt LicenseType) Compare(left string, comparisonFunc func(left, right string) float64) (float64, error)

Compare compares the license template text with the provided text using the given comparison function. Returns the similarity score from the comparison function.

func (LicenseType) GeneratorFunc

func (lt LicenseType) GeneratorFunc() (WriteableGenerator, error)

GeneratorFunc returns the generator function for this license type.

func (LicenseType) RequiresCopyright

func (lt LicenseType) RequiresCopyright() bool

RequiresCopyright returns true if this license type requires copyright information.

func (LicenseType) RequiresNotice

func (lt LicenseType) RequiresNotice() bool

RequiresNotice returns true if this license type requires a NOTICE file.

func (LicenseType) String

func (lt LicenseType) String() string

String returns the string representation of the license type.

func (LicenseType) Template

func (lt LicenseType) Template() (string, error)

Template returns the license text template for this license type.

type NoticeInput

type NoticeInput struct {
	ProjectName string
	Holder      string
	StartYear   int
	EndYear     int
}

NoticeInput contains the information needed to generate a NOTICE file.

type Repository

type Repository interface {
	Load(path string, license *License) error
	Write(license *License) error
}

Repository provides an abstraction for loading and writing licenses from different storage backends

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service provides business logic operations for managing licenses.

func NewService

func NewService(repo Repository) Service

NewService creates a new Service with the given repository.

func (Service) Create

func (s Service) Create(projectName string, holder string, start, end int, licenseType LicenseType) error

Create creates a new license with the given parameters and writes it via the repository.

func (Service) GetLicenseType

func (s Service) GetLicenseType(path string) (LicenseType, error)

GetLicenseType loads a license from the given path and returns its license type.

func (Service) GetYears

func (s Service) GetYears(path string) (CopyrightYears, error)

GetYears loads a license from the given path and returns its copyright years.

func (Service) UpdateEndYear

func (s Service) UpdateEndYear(path string, year int) error

UpdateEndYear loads a license from the given path, updates its copyright end year, and writes it back.

func (Service) UpdateHolder

func (s Service) UpdateHolder(path string, holder string) error

UpdateHolder loads a license from the given path, updates its copyright holder, and writes it back.

func (Service) UpdateProjectName

func (s Service) UpdateProjectName(path string, name string) error

UpdateProjectName loads a license from the given path, updates its project name, and writes it back.

func (Service) UpdateStartYear

func (s Service) UpdateStartYear(path string, year int) error

UpdateStartYear loads a license from the given path, updates its copyright start year, and writes it back.

type Writeable

type Writeable struct {
	Content string
	Path    string
}

Writeable contains license file content and its destination path.

func ApacheGenerator

func ApacheGenerator(projectName *string, cr *Copyright, dest *bytes.Buffer) ([]Writeable, error)

ApacheGenerator generates license files for the Apache License 2.0.

func BoostGenerator

func BoostGenerator(projectName *string, cr *Copyright, dest *bytes.Buffer) ([]Writeable, error)

BoostGenerator generates license files for the Boost Software License 1.0.

func GNULesserGenerator

func GNULesserGenerator(projectName *string, cr *Copyright, dest *bytes.Buffer) ([]Writeable, error)

GNULesserGenerator generates license files for the GNU Lesser General Public License 3.0.

func MITGenerator

func MITGenerator(projectName *string, cr *Copyright, dest *bytes.Buffer) ([]Writeable, error)

MITGenerator generates license files for the MIT license.

func MozillaGenerator

func MozillaGenerator(projectName *string, cr *Copyright, dest *bytes.Buffer) ([]Writeable, error)

MozillaGenerator generates license files for the Mozilla Public License 2.0.

func UnlicenseGenerator

func UnlicenseGenerator(projectName *string, cr *Copyright, dest *bytes.Buffer) ([]Writeable, error)

UnlicenseGenerator generates license files for the Unlicense.

type WriteableGenerator

type WriteableGenerator func(projectName *string, cr *Copyright, dest *bytes.Buffer) ([]Writeable, error)

WriteableGenerator is a function that generates license files for a given license type.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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