ics

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ics writes iCalendar (RFC 5545) files: a VCALENDAR holding VEVENT components, as calendar clients import or subscribe to them.

The package handles the encoding rules that are easy to get wrong: TEXT values are escaped, control characters are dropped, invalid UTF-8 is repaired, content lines are folded at 75 octets without splitting a multi-byte character, and every line ends in CRLF.

No string a program hands over can start a content line of its own. The values that are not TEXT, a status or a class or the value of a Property, lose every control character, line breaks included, and a property or parameter name that is not made of letters, digits and hyphens is an error.

A calendar is written whole or not at all. Calendar.WriteTo reports what stands in the way before it writes anything: a calendar without PRODID, an event without UID or Start or with an End before its Start, an invalid name.

Times

Timed events are written in UTC ("DTSTART:20261110T080000Z"). UTC needs no VTIMEZONE component, and every client shows the instant in the viewer's own zone, so nothing is lost for one-off events. Recurrence rules, which would need a local zone to stay correct across daylight-saving changes, are not supported: write every occurrence as an event of its own.

All-day events are written as dates ("DTSTART;VALUE=DATE:20261224"). The date is read in Calendar.TimeZone when set, or else in the location the time value carries. As in RFC 5545, the end of an all-day event is exclusive: a one-day event on 24 December ends on 25 December, and an End on 24 December is an error. By default, a zero End makes an all-day event last one day.

Calendar.TimeZone is also written as X-WR-TIMEZONE when it has a name calendar clients know, one of the IANA time zone database such as "Europe/Berlin". time.Local and zones made with time.FixedZone have none, so nothing is written for them.

Encoding choices

RFC 5545 leaves some choices to the writer. The defaults suit a new feed; a program that moves an existing feed to this package can set the fields below so the feed keeps its bytes, since subscribed clients see changed bytes as edited events and a changed UID as a new event:

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrEndBeforeStart = errors.New("ics: event ends before it starts")

ErrEndBeforeStart is returned when an event ends before it starts: a timed event whose End is earlier than its Start, or an all-day event whose End, which is exclusive, does not fall on a later date than its Start.

View Source
var ErrInvalidName = errors.New("ics: invalid property or parameter name")

ErrInvalidName is returned when the name of a property or of a parameter is not one RFC 5545 allows: letters, digits and hyphens, and at least one of them. Anything else in a name, a colon or a line break above all, would be read as part of the content line around it.

View Source
var ErrMissingProdID = errors.New("ics: calendar has no PRODID")

ErrMissingProdID is returned when a calendar has no product identifier.

View Source
var ErrMissingStart = errors.New("ics: event has no start")

ErrMissingStart is returned when an event has no Start. A calendar that is published needs one for every event, and the zero time would put the event into the year 1.

View Source
var ErrMissingUID = errors.New("ics: event has no UID")

ErrMissingUID is returned when an event has no UID. RFC 5545 requires one, and clients use it to recognize an event they imported before.

Functions

func EscapeText

func EscapeText(s string) string

EscapeText encodes s as an RFC 5545 TEXT value: backslashes, semicolons and commas are escaped, line breaks become \n, the other control characters but tab are dropped (the C0 controls, DEL and the C1 controls), and invalid UTF-8 is replaced with U+FFFD. RFC 5545 allows the C1 controls, but no calendar shows them, and a terminal the file is printed on takes U+009B for ESC [ and U+009D for ESC ].

func Fold

func Fold(line string) []string

Fold splits one content line into physical lines of at most 75 octets, as RFC 5545 section 3.1 requires: every line after the first starts with the space that marks it a continuation. No multi-byte character is split, and invalid UTF-8 is replaced with U+FFFD first, so every physical line is valid UTF-8. The lines carry no CRLF.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/mittwald/cli-kit/ics"
)

func main() {
	for _, line := range ics.Fold("DESCRIPTION:" + strings.Repeat("abcdefghij", 8)) {
		fmt.Printf("%2d %q\n", len(line), line[:min(len(line), 16)])
	}
}
Output:
75 "DESCRIPTION:abcd"
18 " defghijabcdefgh"

func HashUID

func HashUID(domain string, parts ...string) string

HashUID derives a stable UID from the fields that identify an event, for sources that have no identifier of their own: the same parts always give the same UID, so a client re-importing the calendar updates the events it knows instead of duplicating them. domain should name the program, such as "example.com". The parts are hashed, so they do not leak into the file.

func OccurrenceUID

func OccurrenceUID(uid string, start time.Time) string

OccurrenceUID derives a distinct UID for one occurrence of a series whose occurrences share uid. RFC 5545 forbids two events with the same UID unless a RECURRENCE-ID tells them apart; appending the start keeps each occurrence its own event.

The result is a UID for Event.UID like any other: uid is kept as given, and the calendar that writes the event decides what becomes of it, removing white space and escaping it by default and writing it as it stands with Calendar.VerbatimUIDs. A uid that holds nothing but white space and control characters gives the empty UID, so the event is still reported as ErrMissingUID.

Types

type Calendar

type Calendar struct {
	// ProdID identifies the program that wrote the calendar, as a formal
	// public identifier such as "-//Example//Example CLI//EN". It is required.
	ProdID string
	// Name is the calendar's display name (X-WR-CALNAME). Optional.
	Name string
	// Method is the iTIP method; empty means "PUBLISH", the method for a
	// calendar that is imported or subscribed to. It is written in upper
	// case, without control characters and surrounding white space.
	Method string
	// Scale is the calendar scale; empty means "GREGORIAN". It is written as
	// Method is.
	Scale string
	// TimeZone is the zone all-day dates are read in. Its name is also
	// written as X-WR-TIMEZONE, which some clients use as the calendar's
	// zone, when it is one clients know: a name of the IANA time zone
	// database that time.LoadLocation resolves, such as "Europe/Berlin" or
	// "UTC". time.Local, whose name is "Local", and zones made with
	// time.FixedZone have no such name; they still decide the dates, but no
	// X-WR-TIMEZONE is written for them.
	TimeZone *time.Location
	// Stamp is the DTSTAMP of every event that has none of its own. Zero
	// means the time of writing; set it for reproducible output.
	Stamp time.Time
	// Props are further calendar properties, such as X- properties, written
	// after the standard ones.
	Props []Property
	// Events are the calendar's events, written in order.
	Events []Event

	// EventPropertyOrder lists property names, such as "ORGANIZER", in the
	// order they are written in every event; names are matched regardless of
	// case. Properties it names come first, in its order. The others follow
	// in the default order: UID, DTSTAMP, DTSTART, DTEND, SUMMARY, LOCATION,
	// DESCRIPTION, CATEGORIES, STATUS, TRANSP, CLASS, LAST-MODIFIED and then
	// [Event.Props] as given. Properties that share a name, such as several
	// ATTENDEE, keep their order among themselves. RFC 5545 gives properties
	// no order, so use it to match an existing feed or to put the properties
	// a reader looks for first, such as ORGANIZER and ATTENDEE before STATUS.
	EventPropertyOrder []string
	// MissingEnd says how an event with a zero End is written. The zero
	// value, [EndDefault], leaves DTEND out of a timed event and writes the
	// day after the start for an all-day event.
	MissingEnd EndMode
	// VerbatimUIDs writes every [Event.UID] as given: only the control
	// characters RFC 5545 allows in no content line, the C0 controls but tab
	// and DEL, are removed, and invalid UTF-8 is replaced with U+FFFD. The
	// C1 controls, which RFC 5545 allows, stay, and backslashes, semicolons
	// and commas are not escaped, so a UID keeps the form a feed published.
	// By default, white space and the C1 controls are removed too, and the
	// UID is escaped as the TEXT value it is. Set it when the UIDs come from
	// a scheme of the caller's own that has to stay stable even where it
	// lets white space, C1 controls or the characters TEXT escapes through,
	// such as UIDs a feed has published before: clients key events by UID,
	// so a changed UID duplicates the event in every subscribed client. A
	// UID that is empty or only white space is still [ErrMissingUID].
	VerbatimUIDs bool
}

Calendar is one VCALENDAR object.

func (Calendar) Marshal

func (c Calendar) Marshal() ([]byte, error)

Marshal returns the calendar encoded as an iCalendar file.

func (Calendar) WriteTo

func (c Calendar) WriteTo(w io.Writer) (int64, error)

WriteTo writes the calendar to w as an iCalendar file. It implements io.WriterTo. Nothing is written when the calendar or one of its events cannot be written as it is: without a PRODID (ErrMissingProdID), a UID (ErrMissingUID) or a Start (ErrMissingStart), with an End before the Start (ErrEndBeforeStart), or with a property or parameter name that is not one (ErrInvalidName).

Example
package main

import (
	"os"
	"strings"
	"time"

	"github.com/mittwald/cli-kit/ics"
)

func main() {
	stamp := time.Date(2026, 11, 10, 8, 0, 0, 0, time.UTC)
	cal := ics.Calendar{
		ProdID: "-//Example//Example CLI//EN",
		Name:   "Team",
		Stamp:  stamp,
		Events: []ics.Event{
			{
				UID:         ics.HashUID("example.com", "holiday", "2026-12-24"),
				Start:       time.Date(2026, 12, 24, 0, 0, 0, 0, time.UTC),
				AllDay:      true,
				Summary:     "Christmas Eve",
				Transparent: true,
			},
			{
				UID:     "standup-20261110@example.com",
				Start:   time.Date(2026, 11, 10, 9, 0, 0, 0, time.UTC),
				End:     time.Date(2026, 11, 10, 9, 15, 0, 0, time.UTC),
				Summary: "Standup, daily",
				Props:   []ics.Property{ics.TextProperty("X-EXAMPLE-ROOM", "Blue")},
			},
		},
	}
	var out strings.Builder
	if _, err := cal.WriteTo(&out); err != nil {
		panic(err)
	}
	// Print with LF line ends; the file itself uses CRLF.
	_, _ = os.Stdout.WriteString(strings.ReplaceAll(out.String(), "\r\n", "\n"))
}
Output:
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example//Example CLI//EN
CALSCALE:GREGORIAN
METHOD:PUBLISH
X-WR-CALNAME:Team
BEGIN:VEVENT
UID:b327d0058e593094f8d9821ffa3d7219@example.com
DTSTAMP:20261110T080000Z
DTSTART;VALUE=DATE:20261224
DTEND;VALUE=DATE:20261225
SUMMARY:Christmas Eve
TRANSP:TRANSPARENT
END:VEVENT
BEGIN:VEVENT
UID:standup-20261110@example.com
DTSTAMP:20261110T080000Z
DTSTART:20261110T090000Z
DTEND:20261110T091500Z
SUMMARY:Standup\, daily
TRANSP:OPAQUE
X-EXAMPLE-ROOM:Blue
END:VEVENT
END:VCALENDAR
Example (Participants)

A feed that lists the participants before the status, quotes every name and writes a line break in a name as a space, for clients that do not decode RFC 6868.

package main

import (
	"os"
	"strings"
	"time"

	"github.com/mittwald/cli-kit/ics"
)

func main() {
	name := func(value string) ics.Param {
		return ics.Param{Name: "CN", Value: value, Quote: true, LineBreak: " "}
	}
	cal := ics.Calendar{
		ProdID: "-//Example//Example CLI//EN",
		Stamp:  time.Date(2026, 11, 10, 8, 0, 0, 0, time.UTC),
		EventPropertyOrder: []string{
			"UID", "DTSTAMP", "DTSTART", "DTEND", "SUMMARY", "ORGANIZER", "ATTENDEE",
		},
		Events: []ics.Event{{
			UID:     "planning-20261110@example.com",
			Start:   time.Date(2026, 11, 10, 13, 0, 0, 0, time.UTC),
			End:     time.Date(2026, 11, 10, 14, 0, 0, 0, time.UTC),
			Summary: "Planning",
			Status:  "confirmed",
			Props: []ics.Property{
				{
					Name:   "ATTENDEE",
					Params: []ics.Param{name("Ann Other"), {Name: "PARTSTAT", Value: "ACCEPTED"}},
					Value:  "mailto:ann@example.com",
				},
				{
					Name:   "ORGANIZER",
					Params: []ics.Param{name("Jane Doe\nTeam Lead")},
					Value:  "mailto:jane@example.com",
				},
			},
		}},
	}
	var out strings.Builder
	if _, err := cal.WriteTo(&out); err != nil {
		panic(err)
	}
	_, _ = os.Stdout.WriteString(strings.ReplaceAll(out.String(), "\r\n", "\n"))
}
Output:
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example//Example CLI//EN
CALSCALE:GREGORIAN
METHOD:PUBLISH
BEGIN:VEVENT
UID:planning-20261110@example.com
DTSTAMP:20261110T080000Z
DTSTART:20261110T130000Z
DTEND:20261110T140000Z
SUMMARY:Planning
ORGANIZER;CN="Jane Doe Team Lead":mailto:jane@example.com
ATTENDEE;CN="Ann Other";PARTSTAT=ACCEPTED:mailto:ann@example.com
STATUS:CONFIRMED
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR

type EndMode added in v0.3.0

type EndMode int

EndMode says how an event whose End is zero is written. See Calendar.MissingEnd.

const (
	// EndDefault leaves DTEND out of a timed event, which then ends at its
	// start, and writes the day after the start as the end of an all-day
	// event, which then lasts one day. Values other than the constants below
	// act as EndDefault.
	EndDefault EndMode = iota
	// EndOmit leaves DTEND out of every event without an End. RFC 5545 reads
	// an all-day event without DTEND as lasting one day, so this means the
	// same as EndDefault in one line less; use it where a consumer expects
	// no DTEND it was not given.
	EndOmit
	// EndDerive writes the end RFC 5545 implies: the start of a timed event,
	// the day after the start of an all-day event. Use it for consumers that
	// require DTEND.
	EndDerive
	// EndAsGiven writes the zero End like any other: 00010101T000000Z for a
	// timed event, the date the zero time falls on for an all-day event. No
	// client reads that as a sensible end, and it is not [ErrEndBeforeStart]
	// as an End that is set and lies before the start is; use it only to
	// keep the bytes of a feed whose earlier writer wrote the zero time.
	EndAsGiven
)

type Event

type Event struct {
	// UID identifies the event across exports and is required. White space,
	// a no-break space as much as a space, and control characters are
	// removed, and what is left is escaped as TEXT, so a reader gets back a
	// backslash, a semicolon or a comma in it; [Calendar.VerbatimUIDs]
	// writes the UID as given instead. Occurrences of the same series need
	// distinct UIDs, see [OccurrenceUID].
	UID string
	// Stamp is the event's DTSTAMP; zero falls back to [Calendar.Stamp].
	Stamp time.Time
	// Start is when the event begins. It is required: a zero Start is
	// [ErrMissingStart].
	Start time.Time
	// End is when the event ends, exclusive. By default, zero leaves DTEND
	// out, which makes a timed event end at its start, and makes an all-day
	// event last a day; [Calendar.MissingEnd] chooses otherwise. An End that
	// is set must not lie before Start, and for an all-day event it has to
	// fall on a later date than Start, since the end date is exclusive: an
	// event on 24 December alone ends on 25 December. Anything else is
	// [ErrEndBeforeStart].
	End time.Time
	// AllDay writes Start and End as dates instead of times.
	AllDay bool
	// Summary is the event's title. Empty leaves SUMMARY out.
	Summary string
	// Description is the event's longer text.
	Description string
	// Location is where the event takes place.
	Location string
	// Categories are written as one CATEGORIES property.
	Categories []string
	// Status is an RFC 5545 event status, such as "TENTATIVE" or
	// "CONFIRMED"; empty leaves STATUS out. It is written in upper case,
	// without control characters and surrounding white space.
	Status string
	// Class is "PUBLIC", "PRIVATE" or "CONFIDENTIAL"; empty leaves CLASS out,
	// which clients read as PUBLIC. It is written as Status is.
	Class string
	// Transparent marks the event as not blocking time (TRANSP:TRANSPARENT),
	// as a holiday or an informational entry is. Otherwise it is OPAQUE.
	Transparent bool
	// LastModified is written as LAST-MODIFIED when set.
	LastModified time.Time
	// Props are further event properties, such as ORGANIZER, ATTENDEE or
	// X- properties, written after the standard ones unless
	// [Calendar.EventPropertyOrder] places them.
	Props []Property
}

Event is one VEVENT component.

type Param

type Param struct {
	Name  string
	Value string
	// Quote writes Value as a quoted-string even when it needs none. By
	// default a value is quoted only when it contains ":", ";" or ",", which
	// is all RFC 5545 asks for. Set it for free-text parameters such as CN
	// to match a writer that always quotes them, or so a value keeps one form
	// whatever it contains.
	Quote bool
	// LineBreak, when not empty, replaces each CR and each LF in Value
	// before the value is encoded, so a CRLF pair is replaced twice. Empty
	// keeps line breaks and encodes each, a CRLF pair counted as one, as
	// RFC 6868's "^n". Set it, typically to " ", for consumers that do not
	// decode RFC 6868 and would show "^n" as it stands. The replacement is
	// encoded like the rest of the value.
	LineBreak string
}

Param is one property parameter, such as CN="Jane Doe".

type Property

type Property struct {
	Name   string
	Params []Param
	Value  string
}

Property is one content line: a name, optional parameters, and a value. Name and the names of Params have to be made of letters, digits and hyphens, or writing the calendar fails with ErrInvalidName. Value is written as given but for control characters, line breaks included, which are removed, so a value cannot start a content line of its own; a tab stays. Build TEXT values with TextProperty, which escapes them.

func TextProperty

func TextProperty(name, value string, params ...Param) Property

TextProperty returns a property whose value is TEXT, escaped with EscapeText. Use it for X- properties and other free text.

func (Property) String

func (p Property) String() string

String returns the property as one unfolded content line without CRLF. Names are written in upper case. Parameter values are caret encoded as RFC 6868 describes and quoted when they contain ":", ";" or ",", so they cannot end the parameter early; Param.Quote and Param.LineBreak change that per parameter. Control characters in them are dropped, line breaks and tab aside, as EscapeText drops them. Control characters in the names and in Value are dropped as well, line breaks included, so the result is always one line; String does not check the names any further, which Calendar.WriteTo does.

Jump to

Keyboard shortcuts

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