app

package
v0.0.0-...-6f2c7a1 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2024 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package app contains the functionality that is related to the application layer. This includes all code for the command line interface and the procedures to interact with the runtime environment.

Index

Constants

View Source
const (
	BOOKMARK_DEFAULT_NAME = "default"
	BOOKMARK_PREFIX       = "@"
)
View Source
const (
	BOOKMARKS_FILE_NAME = "bookmarks.json"
	CONFIG_FILE_NAME    = "config.ini"
)

Variables

View Source
var CONFIG_FILE_ENTRIES = []ConfigFileEntries[any]{
	{
		Name: "editor",

		Help: Help{
			Summary: "The CLI command that shall be invoked when running `klog edit`.",
			Value:   "The config property can be any valid CLI command, as you would type it on the terminal. klog will append the target file path as last input argument to that command. Note: you can use quotes in order to prevent undesired shell word-splitting, e.g. if the command name/path contains spaces.",
			Default: "If absent/empty, `klog edit` tries to fall back to the $EDITOR environment variable (which, by the way, takes precedence, if set).",
		},
		// contains filtered or unexported fields
	}, {
		Name: "colour_scheme",

		Help: Help{
			Summary: "The colour scheme of your terminal, so that klog can choose an optimal colour theme for its output.",
			Value:   "The config property must be one of: `dark`, `light`, `basic`, or `no_colour`",
			Default: "If absent/empty, klog assumes a `dark` theme.",
		},
		// contains filtered or unexported fields
	}, {
		Name: "default_rounding",

		Help: Help{
			Summary: "The default value that shall be used for rounding input times via the `--round` flag, e.g. in `klog start --round 15m`.",
			Value:   "The config property must be one of: `5m`, `10m`, `15m`, `30m`, `60m`.",
			Default: "If absent/empty, klog doesn’t round input times.",
		},
		// contains filtered or unexported fields
	}, {
		Name: "default_should_total",

		Help: Help{
			Summary: "The default duration value that shall be used as should-total when creating new records, e.g. in `klog create --should '8h!'`.",
			Value:   "The config property must be a duration followed by an exclamation mark. Examples: `8h!`, `6h30m!`.",
			Default: "If absent/empty, klog doesn’t set a should-total on new records.",
		},
		// contains filtered or unexported fields
	}, {
		Name: "date_format",

		Help: Help{
			Summary: "The preferred date notation for klog to use when adding a new record to a target file, i.e. whether it uses dashes (as in `2022-03-24`) or slashes (as in `2022/03/24`) as delimiter.",
			Value:   "The config property must be either `YYYY-MM-DD` or `YYYY/MM/DD`.",
			Default: "If absent/empty, klog automatically tries to be consistent with what is used in the target file; in doubt, it defaults to the YYYY-MM-DD format.",
		},
		// contains filtered or unexported fields
	}, {
		Name: "time_convention",

		Help: Help{
			Summary: "The preferred time convention for klog to use when adding a new time range entry to a target file, i.e. whether it uses the 24-hour clock (as in `13:00`) or the 12-hour clock (as in `1:00pm`).",
			Value:   "The config property must be either `24h` or `12h`.",
			Default: "If absent/empty, klog automatically tries to be consistent with what is used in the target file; in doubt, it defaults to the 24-hour clock format.",
		},
		// contains filtered or unexported fields
	}, {
		Name: "no_warnings",

		Help: Help{
			Summary: "Whether klog should suppress warnings when processing files.",
			Value:   "The config property must be one of: `UNCLOSED_OPEN_RANGE` (for unclosed open ranges in past records), `FUTURE_ENTRIES` (for records/entries in the future), `OVERLAPPING_RANGES` (for time ranges that overlap), `MORE_THAN_24H` (if there is a record with more than 24h total). Multiple values must be separated by a comma, e.g.: `UNCLOSED_OPEN_RANGE, MORE_THAN_24H`.",
			Default: "If absent/empty, klog prints all available warnings.",
		},
		// contains filtered or unexported fields
	},
}
View Source
var KLOG_CONFIG_FOLDER = []KlogFolder{
	{"KLOG_CONFIG_HOME", ""},
	{"XDG_CONFIG_HOME", "klog"},
	{"HOME", ".config/klog"},
}
View Source
var POTENTIAL_EDITORS = []command.Command{
	command.New("vim", nil),
	command.New("vi", nil),
	command.New("nano", nil),
	command.New("pico", nil),
}
View Source
var POTENTIAL_FILE_EXLORERS = []command.Command{
	command.New("xdg-open", nil),
}

Functions

func IsAbs

func IsAbs(path string) bool

IsAbs checks whether the given path is absolute.

func IsValidBookmarkName

func IsValidBookmarkName(value string) bool

IsValidBookmarkName checks whether `value` is a valid bookmark name (including the prefix).

func NewBookmarksCollectionFromJson

func NewBookmarksCollectionFromJson(jsonText string) (BookmarksCollection, Error)

NewBookmarksCollectionFromJson deserialises JSON data. It returns an error if the syntax is malformed.

func NewConfig

func NewConfig(determined FromDeterminedValues, env FromEnvVars, file FromConfigFile) (Config, Error)

NewConfig creates a new application configuration by merging the config based on the following precedence: (1) env variables, (2) config file, (3) determined values.

func NewFile

func NewFile(path ...string) (File, Error)

NewFile creates a new File object from an absolute or relative path. It returns an error if the given path cannot be resolved.

func NewFileWithContents

func NewFileWithContents(path string, contents string) (FileWithContents, Error)

Types

type AppError

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

func (AppError) Code

func (e AppError) Code() Code

func (AppError) Details

func (e AppError) Details() string

func (AppError) Error

func (e AppError) Error() string

func (AppError) Is

func (e AppError) Is(err error) bool

func (AppError) Original

func (e AppError) Original() error

type BaseParam

type BaseParam[T any] struct {
	// contains filtered or unexported fields
}

type Bookmark

type Bookmark interface {
	// Name is the alias of the bookmark.
	Name() Name

	// Target is the file that the bookmark references.
	Target() File

	// IsDefault returns whether the bookmark is the default one.
	// In this case, the bookmark name is `default`.
	IsDefault() bool
}

Bookmark is a way to reference often used files via a short alias (the name).

func NewBookmark

func NewBookmark(name string, target File) Bookmark

func NewDefaultBookmark

func NewDefaultBookmark(target File) Bookmark

type BookmarksCollection

type BookmarksCollection interface {
	// Get looks up a bookmark by its name.
	Get(Name) Bookmark

	// All returns all bookmarks in the collection.
	All() []Bookmark

	// Default returns the default bookmark of the collection.
	Default() Bookmark

	// Set adds a new bookmark to the collection.
	Set(Bookmark)

	// Remove deletes a bookmark from the collection.
	Remove(Name) bool

	// Clear deletes all bookmarks of the collection.
	Clear()

	// ToJson returns a JSON-representation of the bookmark collection.
	ToJson() string

	// Count returns the number of bookmarks in the collection.
	Count() int
}

BookmarksCollection is the collection of all bookmarks.

func NewEmptyBookmarksCollection

func NewEmptyBookmarksCollection() BookmarksCollection

type Code

type Code int
const (
	// GENERAL_ERROR should be used for generic, otherwise unspecified errors.
	GENERAL_ERROR Code = iota + 1

	// NO_INPUT_ERROR should be used if no input was specified.
	NO_INPUT_ERROR

	// NO_TARGET_FILE should be used if no target file was specified.
	NO_TARGET_FILE

	// IO_ERROR should be used for errors during I/O processes.
	IO_ERROR

	// CONFIG_ERROR should be used for config-folder-related problems.
	CONFIG_ERROR

	// NO_SUCH_BOOKMARK_ERROR should be used if the specified an unknown bookmark name.
	NO_SUCH_BOOKMARK_ERROR

	// NO_SUCH_FILE should be used if the specified file does not exit.
	NO_SUCH_FILE

	// LOGICAL_ERROR should be used syntax or logical violations.
	LOGICAL_ERROR
)

func (Code) ToInt

func (c Code) ToInt() int

ToInt returns the numeric value of the error. This is typically used as exit code.

type Config

type Config struct {
	// IsDebug indicates whether klog should print additional debug information.
	// This is an ephemeral property, which is used for debugging purposes, and not
	// supposed to be configured permanently.
	IsDebug MandatoryParam[bool]

	// Editor is the CLI command with which to invoke the preferred editor.
	Editor OptionalParam[string]

	// ColourScheme specifies the background of the terminal, so that
	// the output colours can be adjusted accordingly.
	ColourScheme MandatoryParam[tf.ColourTheme]

	// CpuKernels is the number of available CPUs that klog is allowed to utilise.
	// The value must be `1` or higher.
	// This is a low-level property that is not supposed to be exposed to end-users at all.
	CpuKernels MandatoryParam[int]

	// DefaultRounding is the default for the --round flag.
	DefaultRounding OptionalParam[service.Rounding]

	// DefaultShouldTotal is the default should total for new records.
	DefaultShouldTotal OptionalParam[klog.ShouldTotal]

	// DateUseDashes denotes the preferred date format: YYYY-MM-DD (true) or YYYY/MM/DD (false).
	DateUseDashes OptionalParam[bool]

	// TimeUse24HourClock denotes the preferred time format: 13:00 (true) or 1:00pm (false).
	TimeUse24HourClock OptionalParam[bool]

	// NoWarnings indicates klog should suppress any warning types.
	NoWarnings OptionalParam[service.DisabledCheckers]
}

Config contain all variable settings that influence the behaviour of the application. Some of these properties can be controlled by the user in one way or the other, depending on their purpose.

func NewDefaultConfig

func NewDefaultConfig(c tf.ColourTheme) Config

type ConfigFileEntries

type ConfigFileEntries[T any] struct {
	Name string
	Help Help
	// contains filtered or unexported fields
}

func (ConfigFileEntries[T]) Value

func (e ConfigFileEntries[T]) Value(c Config) string

type Context

type Context interface {
	// Print prints to stdout.
	Print(string)

	// ReadLine reads user input from stdin.
	ReadLine() (string, Error)

	// KlogConfigFolder returns the path of the klog config folder.
	KlogConfigFolder() File

	// Meta returns miscellaneous meta information.
	Meta() Meta

	// ReadInputs retrieves all input from the given file or bookmark names.
	ReadInputs(...FileOrBookmarkName) ([]klog.Record, Error)

	// RetrieveTargetFile returns the desired file, requiring that there is exactly one.
	RetrieveTargetFile(fileArg FileOrBookmarkName) (FileWithContents, Error)

	// ReconcileFile applies one or more reconcile handlers to a file and saves it.
	ReconcileFile(FileOrBookmarkName, []reconciling.Creator, ...reconciling.Reconcile) (*reconciling.Result, Error)

	// Now returns the current timestamp.
	Now() gotime.Time

	// ReadBookmarks returns all configured bookmarks of the user.
	ReadBookmarks() (BookmarksCollection, Error)

	// ManipulateBookmarks saves a modified bookmark collection.
	ManipulateBookmarks(func(BookmarksCollection) Error) Error

	// Execute attempts to run a command on the system.
	Execute(command.Command) Error

	// Editors returns commands to launch a text editor on the system.
	// - The string is a user-specified command, if specified.
	// - The command list is a prioritised list of predefined commands.
	Editors() (string, []command.Command)

	// FileExplorers returns commands to launch a file explorer on the system.
	FileExplorers() []command.Command

	// Serialise returns the current styler + serialiser according to the user’s
	// style preferences.
	Serialise() (tf.Styler, TextSerialiser)

	// ConfigureSerialisation changes serialisation properties.
	ConfigureSerialisation(func(tf.Styler, bool) (tf.Styler, bool))

	// Debug takes a void function that is only executed in debug mode.
	Debug(func())

	// Config returns the current preferences.
	Config() Config
}

Context is a representation of the runtime environment of klog. The commands carry out all side effects via this interface.

func NewContext

func NewContext(klogFolder File, meta Meta, styler tf.Styler, cfg Config) Context

NewContext creates a new Context object.

type Error

type Error interface {
	// Error returns the error message.
	Error() string

	Is(error) bool

	// Details returns additional details, such as a hint how to solve the problem.
	Details() string

	// Original returns the original underlying error, if it exists.
	Original() error

	// Code returns the error code.
	Code() Code
}

Error is a representation of an application error.

func ApplyReconciler

func ApplyReconciler(records []klog.Record, blocks []txt.Block, creators []reconciling.Creator, reconcile ...reconciling.Reconcile) (*reconciling.Result, Error)

func CreateEmptyFile

func CreateEmptyFile(file File) Error

CreateEmptyFile creates a new file on disk. It returns an error if the file already exists, or if the file cannot be created.

func NewError

func NewError(message string, details string, original error) Error

func NewErrorWithCode

func NewErrorWithCode(code Code, message string, details string, original error) Error

func ReadFile

func ReadFile(source File) (string, Error)

ReadFile reads the contents of a file from disk and returns it as string. It returns an error if the file doesn’t exit or cannot be read.

func ReadStdin

func ReadStdin() (string, Error)

ReadStdin reads the entire input from stdin and returns it as string. It returns an error if stdin cannot be accessed, or if reading from it fails.

func WriteToFile

func WriteToFile(target File, contents string) Error

WriteToFile saves contents in a file on disk. It returns an error if the file cannot be written.

type File

type File interface {
	// Name returns the file name.
	Name() string

	// Location returns the path of the folder, where the file resides.
	Location() string

	// Path returns the path of the file.
	Path() string
}

File is a descriptor for a file. The file is not guaranteed to actually exist on disk.

func Join

func Join(f File, fileOrFolderName string) File

func NewFileOrPanic

func NewFileOrPanic(absolutePath string) File

NewFileOrPanic creates a new File object. It panics, if the path is not absolute.

type FileOrBookmarkName

type FileOrBookmarkName string

FileOrBookmarkName is either a file name or a bookmark name as specified as argument on the command line.

type FileRetriever

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

func (*FileRetriever) Retrieve

func (retriever *FileRetriever) Retrieve(fileArgs ...FileOrBookmarkName) ([]FileWithContents, Error)

Retrieve retrieves the contents from files or bookmarks. If no arguments were specified, it tries to read from the default bookmark.

type FileWithContents

type FileWithContents interface {
	File

	// Contents returns the contents of the file.
	Contents() string
}

FileWithContents is like File, but with the file contents attached to it.

type FromConfigFile

type FromConfigFile struct {
	FileContents string
}

FromConfigFile is the part of the configuration that the user can control via a configuration file.

func (FromConfigFile) Apply

func (e FromConfigFile) Apply(config *Config) Error

type FromDeterminedValues

type FromDeterminedValues struct {
	NumCpus int
}

FromDeterminedValues is the part of the configuration that is automatically determined, e.g. by constraints of the runtime environment.

func (FromDeterminedValues) Apply

func (e FromDeterminedValues) Apply(config *Config) Error

type FromEnvVars

type FromEnvVars struct {
	GetVar func(string) string
}

FromEnvVars is the part of the configuration that is determined by environment variables.

func (FromEnvVars) Apply

func (e FromEnvVars) Apply(config *Config) Error

type Help

type Help struct {
	Summary string
	Default string
	Value   string
}

type KlogFolder

type KlogFolder struct {
	BasePathEnvVar string
	Location       string
}

func (KlogFolder) EnvVarSymbol

func (kf KlogFolder) EnvVarSymbol() string

type MandatoryParam

type MandatoryParam[T any] struct {
	BaseParam[T]
}

func (MandatoryParam[T]) Value

func (p MandatoryParam[T]) Value() T

type Meta

type Meta struct {

	// Specification contains the file format specification in full text.
	Specification string

	// License contains the license text.
	License string

	// Version contains the release version, e.g. `v2.7`.
	Version string

	// SrcHash contains the hash of the sources that the binary was built from.
	SrcHash string
}

Meta holds miscellaneous information about the klog binary.

type Name

type Name string

Name is the bookmark alias.

func NewName

func NewName(name string) Name

func (Name) Value

func (n Name) Value() string

Value returns the name of the bookmark without prefix.

func (Name) ValuePretty

func (n Name) ValuePretty() string

ValuePretty returns the name of the bookmark with prefix.

type OptionalParam

type OptionalParam[T any] struct {
	BaseParam[T]
	// contains filtered or unexported fields
}

func (OptionalParam[T]) Unwrap

func (p OptionalParam[T]) Unwrap(f func(T))

func (OptionalParam[T]) UnwrapOr

func (p OptionalParam[T]) UnwrapOr(defaultValue T) T

type ParserErrors

type ParserErrors interface {
	Error
	All() []txt.Error
}

func NewParserErrors

func NewParserErrors(errs []txt.Error) ParserErrors

type Reader

type Reader interface {
	Apply(*Config) Error
}

type Retriever

type Retriever func(fileArgs ...FileOrBookmarkName) ([]FileWithContents, Error)

Retriever is the function interface for retrieving the input data from various kinds of sources.

type StdinRetriever

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

func (*StdinRetriever) Retrieve

func (retriever *StdinRetriever) Retrieve(fileArgs ...FileOrBookmarkName) ([]FileWithContents, Error)

Retrieve retrieves the content from stdin. It only returns something if no file or bookmark names were specified explicitly.

type TextSerialiser

type TextSerialiser struct {
	DecimalDuration bool
	Styler          tf.Styler
}

TextSerialiser is a specialised parser.Serialiser implementation for the terminal.

func NewSerialiser

func NewSerialiser(styler tf.Styler, decimal bool) TextSerialiser

func (TextSerialiser) Date

func (cs TextSerialiser) Date(d klog.Date) string

func (TextSerialiser) Duration

func (cs TextSerialiser) Duration(d klog.Duration) string

func (TextSerialiser) OpenRange

func (cs TextSerialiser) OpenRange(or klog.OpenRange) string

func (TextSerialiser) Range

func (cs TextSerialiser) Range(r klog.Range) string

func (TextSerialiser) ShouldTotal

func (cs TextSerialiser) ShouldTotal(d klog.Duration) string

func (TextSerialiser) SignedDuration

func (cs TextSerialiser) SignedDuration(d klog.Duration) string

func (TextSerialiser) Summary

func (cs TextSerialiser) Summary(s parser.SummaryText) string

func (TextSerialiser) Time

func (cs TextSerialiser) Time(t klog.Time) string

Directories

Path Synopsis
cli
Package cli contains handlers for all available commands.
Package cli contains handlers for all available commands.
report
Package report is a utility for the report command.
Package report is a utility for the report command.
Package klog is the entry point of the command line tool.
Package klog is the entry point of the command line tool.

Jump to

Keyboard shortcuts

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