Compare commits

...

No commits in common. "stable" and "b0f6628817e4d705d1b5c4268b06ebd3a785e85d" have entirely different histories.

45 changed files with 467 additions and 4698 deletions

127
.gitignore vendored
View file

@ -1,127 +0,0 @@
# Created by https://www.toptal.com/developers/gitignore/api/go,linux,emacs,macos
# Edit at https://www.toptal.com/developers/gitignore?templates=go,linux,emacs,macos
### Emacs ###
# -*- mode: gitignore; -*-
*~
\#*\#
/.emacs.desktop
/.emacs.desktop.lock
*.elc
auto-save-list
tramp
.\#*
# Org-mode
.org-id-locations
*_archive
# flymake-mode
*_flymake.*
# eshell files
/eshell/history
/eshell/lastdir
# elpa packages
/elpa/
# reftex files
*.rel
# AUCTeX auto folder
/auto/
# cask packages
.cask/
dist/
# Flycheck
flycheck_*.el
# server auth directory
/server/
# projectiles files
.projectile
# directory configuration
.dir-locals.el
# network security
/network-security.data
### Go ###
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
### Linux ###
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### macOS Patch ###
# iCloud generated files
*.icloud
# End of https://www.toptal.com/developers/gitignore/api/go,linux,emacs,macos
/my-log
cover.html
cmd/test.go

262
AGENTS.md
View file

@ -1,56 +1,222 @@
# Agent Guidelines for my-log
# AGENTS.md - Development Guidelines for my-log-wynter
## Build/Test/Lint Commands
- Build: `make build` or `go build -o my-log`
- Test all: `make test` (runs fmt + test with race + coverage)
- Test single: `go test ./path/to/package -run TestName`
- Format: `make fmt` or `go fmt ./...`
- Coverage report: `make report` (generates cover.html)
## Project Overview
## Code Style
- **Module**: `codeberg.org/danjones000/my-log`
- **Go version**: 1.21.5
- **Imports**: Standard library first, then external packages, then local packages. Use short aliases for common imports (e.g., `fp` for `path/filepath`, `mapst` for `mitchellh/mapstructure`)
- **Formatting**: Always run `go fmt` before commits (included in test target)
- **Types**: Use explicit types (e.g., `int64`, `float64`). Convert numbers appropriately when unmarshaling JSON
- **Naming**: PascalCase for exported, camelCase for unexported. Use descriptive names
- **Don't reinvent the wheel**: Use standard library functions (e.g., `slices.Contains` instead of custom contains functions)
- **Error handling**: Return wrapped errors with context. Define custom errors in models/errors.go. Use `ErrorIs` for error checking
- **Testing**: Use github.com/nalgeon/be. Table-driven tests with helper functions. Test both marshal/unmarshal for encoding types. Use `t.ArtifactDir()` instead of `t.TempDir()` and `t.Context()` instead of `context.Background()`
- **Concurrency**: Use channels and goroutines with WaitGroups for parallel processing (see entry.go patterns)
- **Comments**: Include license header on cmd files. Document exported functions and types
my-log-wynter is a Go CLI application that extends the `codeberg.org/danjones000/my-log` CLI library with custom commands. It integrates with youtube-dl/yt-dlp for video metadata fetching. It uses and `github.com/lrstanley/go-ytdlp` for yt-dlp integration.
## Config System
- Viper instance is stored in context using a custom key type (`confKeyType`)
- Use `config.New(ctx, path)` to create a new viper instance
- Use `config.RetrieveFromContext(ctx)` to get both viper and the unmarshaled Config struct
- Formatters can use `v.Sub("formatters." + kind)` to get their own sub-config and unmarshal into their specific config struct
- Test files must create viper instances and add them to context using `config.AddToContext`
## Build/Lint/Test Commands
### Building
```bash
# Build all packages
go build ./...
# Build the CLI binary
go build -o my-log ./cmd/my-log
# Run the CLI
go run ./cmd/my-log
```
### Testing
```bash
# Run all tests
go test ./...
# Run a single test by name
go test -run <TestName> ./...
# Run tests with verbose output
go test -v ./...
# Run tests with coverage
go test -cover ./...
# Run benchmarks
go test -bench=. ./...
```
### Linting
```bash
# Run golangci-lint (comprehensive linter)
golangci-lint run ./...
# Run golangci-lint with auto-fix
golangci-lint run ./... --fix
# Run go vet
go vet ./...
# Format code (gofmt)
gofmt -w .
gofmt -d .
# Check for unused imports and other issues
goimports -w .
```
### Dependencies
```bash
# Update dependencies
go get -u ./...
# Tidy go.mod
go mod tidy
# List dependencies
go list -m all
```
## Code Style Guidelines
### General Conventions
- Follow [Effective Go](https://go.dev/doc/effective_go) and [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments)
- Use Go 1.26.0 or later (as specified in go.mod)
- Run `go fmt` and `gofmt` before committing
- Run `golangci-lint run ./...` before committing
### Naming Conventions
- **Packages**: Use short, lowercase names (e.g., `ytdlp`, not `yt-dlp` or `youtube_dlp`)
- **Variables/Functions**: Use camelCase (e.g., `fetchURL`, not `fetch_url`)
- **Exported Functions/Types**: Use PascalCase (e.g., `Fetch`, not `fetch`)
- **Constants**: Use PascalCase (e.g., `MaxRetries`) or camelCase for unexported (e.g., `maxRetries`)
- **Acronyms**: Keep original casing (e.g., `URL`, not `Url`; `ID`, not `Id`)
- **Files**: Use lowercase with underscores for multiple words (e.g., `fetch_video.go`)
### Import Organization
Imports should be organized in three groups separated by blank lines:
1. Standard library packages
2. External/third-party packages
3. Internal packages (if applicable)
```go
import (
"context"
"fmt"
"os"
"codeberg.org/danjones000/my-log/cli"
"github.com/lrstanley/go-ytdlp"
)
```
### Error Handling
- Return errors where possible; avoid panics except for truly unrecoverable conditions
- Wrap errors with context using `fmt.Errorf("description: %w", err)` or `%v`
- Handle errors explicitly; don't ignore them with `_`
- Place error checks immediately after the operation that can fail
```go
// Good
result, err := fetchURL(ctx, url)
if err != nil {
return nil, fmt.Errorf("failed to fetch %s: %w", url, err)
}
// Avoid
result, _ := fetchURL(ctx, url) // Don't ignore errors
```
### Context Usage
- Pass `context.Context` as the first parameter for functions that may timeout or be cancelled
- Use `context.Background()` for top-level operations and `context.WithTimeout()` for bounded operations
- Check for context cancellation with `ctx.Err()` when appropriate
```go
func Fetch(ctx context.Context, url string) (*Result, error) {
// ...
}
```
### Types and Interfaces
- Define interfaces close to where they are used
- Prefer concrete types unless interface polymorphism is needed
- Use pointer receivers (`*T`) for methods that modify the receiver or when nil is meaningful
### Testing Conventions
- Test files should be named `*_test.go`
- Test functions should start with `Test` (e.g., `TestFetch`)
- Benchmark functions should start with `Benchmark` (e.g., `BenchmarkFetch`)
- Use the github.com/nalgeon/be for assertions: `be.Equal`, `be.Err`, and `be.True`
- Use table-driven tests when testing multiple cases:
```go
func TestFetch(t *testing.T) {
tests := []struct {
name string
url string
wantErr bool
}{
{"valid youtube", "https://youtube.com/watch?v=xxx", false},
{"invalid url", "not-a-url", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// test logic
be.Equal(t, 2*5, 10)
be.True(t, !false)
be.Err(t, err, nil) // No error
be.Err(t, ioErr, io.EOF) // ioErr should be an io.EOF
be.Err(t, otherErr, "bad stuff") // error message contains "bad stuff"
})
}
}
```
### Concurrency
- Use goroutines with `go` keyword for concurrent operations
- Use `sync.WaitGroup` or channels for synchronization
- Prefer `errgroup` for coordinating multiple goroutines with error handling
- Never leak goroutines; ensure they can complete or be cancelled
### Documentation
- Document exported functions, types, and constants with doc comments
- Comments should start with the identifier name (no need to repeat the name)
- Keep comments concise but explanatory
```go
// Fetch retrieves video metadata from yt-dlp compatible sources.
func Fetch(ctx context.Context, url string) (*Info, error) {
// ...
}
```
### Logging
- Print user-friendly messages to stderr
## Project Structure
```
my-log-wynter/
├── cmd/my-log/ # CLI entry point
│ └── main.go
├── ytdlp/ # yt-dlp integration package
│ └── fetch.go
├── go.mod
├── go.sum
└── AGENTS.md # This file
```
## Common Tasks
### Adding a new command
1. Add the command to the my-log library (this project imports it)
2. Update this repository's code as needed
### Adding a new yt-dlp feature
1. Modify `ytdlp/fetch.go`
2. Add tests in `ytdlp/fetch_test.go`
3. Run tests with `go test -v ./ytdlp/`
## Pre-commit Checklist
- [ ] Code is formatted: `gofmt -w .`
- [ ] Imports are organized: `goimports -w .`
- [ ] No lint errors: `golangci-lint run ./...`
- [ ] Tests pass: `go test ./...`
- [ ] Code builds: `go build ./...`
## Git Commit Guidelines
- **Format**: Prepend commit messages with a gitmoji emoji (see https://gitmoji.dev)
- **Style**: Write detailed commit messages that explain what changed and why
- **Examples**: `✨ Add JSON export functionality for log entries`, `🐛 Fix date parsing for RFC3339 timestamps`, `📝 Update README with configuration examples`
## Git Flow Workflow
- **Main branches**: `stable` (production-ready), `develop` (integration branch)
- **Development**: Always commit new features/fixes to `develop` branch or appropriate feature branches
- **Branch prefixes**:
- `feat/feature-name` - New features, merge to `develop` when complete
- `bug/bug-name` - Bug fixes (non-urgent), merge to `develop` when complete
- `hot/version` - Hotfixes for production issues, merge to **both** `stable` and `develop`
- `rel/version` - Release preparation branches
- **Version tags**: Prefix all version tags with `v` (e.g., `v1.0.2`, `v0.0.6`)
- **Releases**: Update CHANGELOG.md with a summary of changes for each new version
- **Never commit directly to**: `stable` branch (only merge from `rel/` or `hot/` branches)
- **Before starting work**: Ensure you're on `develop` branch or create an appropriate feature branch from it
## Project Structure
- `cmd/my-log/`: Main application entrypoint
- `internal/testutil/bep`: Reusable test assertions to complement those used by github.com/nalgeon/be
- `cli/`: Cobra commands (root, drop, config)
- `models/`: Core types (Entry, Log, Meta) with marshal/unmarshal implementations
- `config/`: TOML-based configuration with viper, env overrides, and context propagation
- `formatters/`: Output formatters (plain, json, null) with their own sub-configs
- `files/`: File operations (append)
- `tools/`: Utilities (date parsing, string parsing, write buffers)
- Do not commit files not yet staged unless explicitly asked to do so.

View file

@ -1,104 +0,0 @@
# Changelog
## [0.3.1] - 2026-03-09
- Add AddFormatter function to allow custom builds to register new formatters
- Add option to print config from config command
- Allow MYLOG_CONFIG_PATH to override the config path
## [0.3.0] - 2026-03-09
- Refactor configuration to use viper with context propagation instead of global variables
- Allow formatters to use sub-config with their own config structs
- Move preferred formatter to its own config field in formatters section
- Update AGENTS.md with config system changes and testing guidelines
## [0.2.0] - 2026-03-07
- Add ID field to Entry struct with auto-generation on marshal/unmarshal
- Upgrade mapstructure to maintained fork
## [0.1.1] - 2026-03-01
- Add Time method to Date struct for accessing internal timestamp
- Add Makefile targets for go vet and go fix
- Use named struct fields in tests
- Apply go fix improvements (use maps.Copy, strings.CutPrefix, bytes.Cut, range over int)
## [0.1.0] - 2026-02-28
- ✨ Move CLI commands to cli/ package for extensibility
- Export RootCmd, DropCmd, and ConfigCmd for custom app creation
## [0.0.11] - 2026-02-13
- ✨ Add support for mixed-level nested keys with dot/blank handling
- ✨ Refactor append_test to use standalone test functions
- ✨ Migrate from testify to nalgeon/be testing library
- ✨ Add bep.JSON helper for JSON assertion in tests
## [0.0.10] - 2026-02-10
- ✨ Implement full support for nested fields in Meta and Entry marshalling
- ✨ Add support for nested fields in log entries and JSON marshalling
- ✨ Ensure an id is included when serializing a log entry
- 📝 Add documentation for nested fields
- 🐛 Fix test assertions for added id field and entry serialization
## [0.0.9] - 2026-02-01
- ✨ Add Set method to Metas type
## [0.0.8] - 2026-02-01
- ✨ Add Get method to Metas type
## [0.0.7] - 2025-11-05
- 🚚 Refactor project structure to follow standard Go layout (cmd/my-log/ and internal/cmd/)
- 📝 Add AGENTS.md with comprehensive guidelines for coding agents
- ⚡️ Performance improvement: compile regexes only once
- ✨ Add support for bang prefix to skip value parsing
- 🐛 Fix bang trimming in output
- 🔨 Fix Makefile for Darwin compatibility
- ✏️ Fix Makefile to avoid unnecessary reruns
- ✅ Fix TestMkdirErr on Darwin
## [0.0.6] - 2024-10-07
- Update external dependency: go-dateparser
## [0.0.5] - 2024-10-07
- Small change: adds --output_json to drop command.
## [0.0.4] - 2024-05-08
- ✨ Add -p flag to config to print config path
## [0.0.3] - 2024-03-11
- ✨ Add JSON formatter
- 💥 Breaking change: renamed output.stdout.config value formatter to format
## [0.0.2] - 2024-03-09
- ✨ Use plain formatter to output entry from drop
- ✨ Add newline to file when needed
## [0.0.1] - 2024-03-02
🎉 Initial release.
For this first release, we only have the initial `my-log drop` command implemented, which adds the ability to add new entries to a log.
We also have `my-log config` to create the initial config file.
Parsing the log files will be added to a future release, but the generated logs are compatible with [droplogger](https://github.com/goodevilgenius/droplogger), which can still be used.
### Added
- `my-log drop`: adds a new log entry
- `my-log config`: copies the default config to the default file location

661
LICENSE
View file

@ -1,661 +0,0 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

View file

@ -1,57 +0,0 @@
SOURCES = $(wildcard *.go) $(wildcard **/*.go)
OUT=my-log
GOBIN=$(shell go env GOBIN)
COVEROUT=cover.out
COVERHTML=cover.html
OPEN=xdg-open
OS=$(shell uname -s)
ifeq ($(OS),Darwin)
OPEN=open
endif
.PHONY: help
help: ## Show help for documented recipes
@echo "Make recipes:"
@echo
@grep -E '^[a-zA-Z0-9_#-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
.PHONY: clean
clean: ## Removes temporary and build files
rm -v $(COVEROUT) $(COVERHTML) $(OUT) || true
.PHONY: fmt ## Runs go fmt
fmt: $(SOURCES) ## Runs go fmt
go fmt ./...
.PHONY: fix ## Run go fix
go fix ./...
.PHONY: vet ## Runs go vet
vet: fmt fix
go vet ./...
.PHONY: test
test: ## Test application and generate coverage report
$(MAKE) clean
$(MAKE) $(COVEROUT)
$(COVEROUT): $(SOURCES)
$(MAKE) fmt
go test ./... -race -cover -coverprofile $@
$(COVERHTML): $(COVEROUT)
go tool cover -html=$< -o $@
.PHONY: report
report: $(COVERHTML) ## Generate a coverage report
.PHONY: open-report
open-report: $(COVERHTML) ## Open the coverage report in the default browser
$(OPEN) $<
.PHONY: build
build: $(OUT) ## Builds the application
$(OUT): $(SOURCES) fmt
go build -o $@ ./cmd/my-log

192
README.md
View file

@ -1,192 +0,0 @@
# my-log
`my-log` is a tool for generating and parsing log files for whatever you want. This is early in development. Check our Roadmap before for what's working.
I originally wrote [DropLogger](https://github.com/goodevilgenius/droplogger) to serve this purpose. DropLogger was originally designed to work primarily with IFTTT and Dropbox. Due to IFTTT changing their service significantly since I originally signed up, I no longer use it. Even without IFTTT, DropLogger is a great tool.
So, why did I decide to completely rewrite it? Mainly because DropLogger is written in Python. While Python is a great language, I haven't used it seriously for many years, and I didn't find a whole lot of motivation to add new features to DropLogger, due to this. But I've been working in go for the past six months, and have kind of fell in love with the language. I'd been considering a rewrite of DropLogger for a while, so I decided to help myself get more practice in go by rewriting DropLogger in it.
So, how does this work?
Currently, it mostly doesn't. `my-log` is still in its early stages, and DropLogger is still needed for most of the functionality. So, how will it work?
## Log files
We start with the individual log files. These were designed to be very flexible so that they could be written using a number of different tools. Originally, IFTTT recipes were created that would write to files in Dropbox, but this could be adapted to a number of other automation tools to automatically write as things happen.
What things? Well, maybe you use Tasker to trigger an action when you get home. You might want to keep a log of whenever you arrive at your house. Or, maybe you use [Last.FM](https://www.last.fm/home) to keep track of your music listening habits, and you want to log whenever you listen to a music track. You could create a Zap in Zapier that responds to new scrobbles on Last.FM, and adds those scrobbles to a file.
### Log format
As I mentioned, the format is intended to be very easy to write. Here's a sample:
```
@begin January 12, 2024 at 2:34PM - Title
@key value
@longKey this entry is long, and
spans multiple lines
@number 4
@bool true
@end
```
So, each entry starts with `@begin` and ends with `@end`. It must have a date and a title. It may also have additional data which is indicated by an `@` at the beginning of the line. If I were to convert this to JSON (which `my-log` can do for you), it would look like:
```json
{
"title": "Title",
"date": "2024-01-12T14:34:00Z",
"key": "value",
"longKey": "this entry is long, and\nspans multiple lines",
"number": 4,
"bool": true
}
```
A couple things to note:
- When outputting JSON, the date is converted to ISO-8601 format. The timezone used (if none was given in the original log) is your own local time.
- The newline in the `longKey` was preserved
- Different types are recognized and parsed correctly. It supports the following types:
+ string (default)
+ numbers
+ boolean values (true or false)
+ dates and times
+ A null value (the string "null", "nil", "none", or "~")
+ A raw JSON object/array
Since the extra fields are optional, the simplest log entry can be on a single line. For example, you might have a log file called `notes.txt` with this:
```
@begin February 3, 2015 at 01:33PM - Remember to call Mom @end
@begin February 4, 2015 at 07:45AM - Breakfast today was great! @end
```
As JSON, that would be:
```json
[{
"title":"Rember to call Mom",
"date":"2015-02-03T13:33:00Z"
},{
"title":"Breakfase today was great!",
"date":"2015-02-04T07:45:00Z"
}]
```
#### Nested fields
This format also supports deeper structures. Of course, you can use raw JSON, like this:
```
@begin February 3, 2015 at 01:33PM - Check-in at Piggly Wiggly
@metadata {"lat":"33.6798911","lng":"-84.3959460","shop":"supermarket","osm_id":11617197123,"osm_type":"node","copyright":"The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."}
@url https://www.openstreetmap.org/node/11617197123 @end
```
This becomes exactly what you expect:
```json
{
"title":"Check-in at Piggly Wiggly",
"date":"2015-02-03T13:33:00Z",
"metadata":{"lat":"33.6798911","lng":"-84.3959460","shop":"supermarket","osm_id":11617197123,"osm_type":"node","copyright":"The data included in this document is from www.openstreetmap.org. The data is made available under ODbL."},
"url":"https://www.openstreetmap.org/node/11617197123"
}
```
This `metadata` field is a bit clunky, though. We can expand it into multiple fields for better readability:
```
@begin February 3, 2015 at 01:33PM - Check-in at Piggly Wiggly
@metadata:lat 33.6798911
@metadata:lng -84.3959460
@metadata:shop supermarket
@metadata:osm_id 11617197123
@metadata:osm_type node
@metadata:copyright The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.
@url https://www.openstreetmap.org/node/11617197123 @end
```
In addition to improving readability, it may be more suitable for generation by other tools.
### Adding log entries
As was previously noted, the idea is that you can figure out the best way for you to add to the log file. But, `my-log` also comes with a command to add them from the command line. Run `my-log drop --help` for instructions on how to use it. But, here's a few examples:
```shell
my-log drop notes "Hello"
# Adds "@begin <date> - Hello @end" to notes.txt file
my-log drop -d "yesterday" calls "Talked with Jeremy" -f phone_number=+1-555-867-5309
# If today is January 2, 2024, adds the follow entry to calls.txt
# @begin January 1, 2024 at 12:00:00AM UTC - Talked with Jeremy
# @phone_number +1-555-867-5309 @end
my-log drop -d "1999-12-31T23:59:59Z" events "The end of the world" -f notes="As we know it" -j '{"artist":"R.E.M","slaps":true}'
# Adds the following entry to events.txt
# @begin December 31, 1999 at 11:59:59PM UTC - The end of the world
# @notes As we know it
# @artist R.E.M
# @slaps true @end
```
## Output
This is a work in progress. More info coming soon. Short version is, we want to be able to output to multiple formats in multiple places.
Check [DropLogger's documentation](https://github.com/goodevilgenius/droplogger?tab=readme-ov-file#output) for info on how we want to make it work.
## Configuration
We use a TOML file for configuration. The default location on Linux is ~/.config/my-log/config.toml. You can find the exact location by doing `my-log -h` and looking at the help for the `--config` flag. Running `my-log config` will save the default config file to the default location. The file is intended to be edited by hand. There is no mechanism within the program to modify the file, aside from saving the default one.
The default one has comments to help you out, but here's the options:
### `[input]`
- `path`: The path to where the logs are located. This is usually ~/my-log, but if you want to store it in Dropbox, you might want it to be ~/Dropbox/my-log
- `ext`: The file extension for log files. This is usually txt, which makes it easier to work with multiple tools, but you can change it to log, or my-log, if you want. If you set it to an empty string, no extension will be used, which also means that when parsing the log files, it will look at all files in the folder.
- `recurse`: Whether to look in sub-folders.
### `[output.which-one]`
Each separate output has its own set of configuration. So, replace `which-one` with the output name.
- `enabled`: if set to false, will skip that output when running.
- `config`: This is an output-specific set of settings
#### `[output.stdout.config]`
*This section may change in the near future. We're considering supporting multiple formats.*
- `format`: Which formatter to use when outputting data. This value is also used by `my-log drop` to output the new entry.
### `[formatters]`
Some formatters may have custom configuration.
#### `[formatters.json]`
- `pretty_print`: If true, JSON output will be pretty printed. If false, it will be printed to a single line.
## Roadmap
- [x] `drop` command. This is functional, and supports all the features of `drop-a-log`
+ [x] Don't add an extra blank line before new entries
+ [x] Add a new line at the end
- [ ] Output log entries
+ [ ] A single date
+ [ ] a specific period of time
+ [ ] filter to specific logs
+ [ ] stdout
- [x] plain text
- [x] JSON
- [ ] YAML
- [ ] Other formats? Submit an issue!
+ [ ] file output
- [ ] Any format that stdout supports
- [ ] Multiple formats at once
- [ ] RSS
- [ ] ATOM
+ [ ] sqlite database
- [ ] Maybe: plug-in system to add formats or output destinations

View file

@ -1,87 +0,0 @@
/*
Copyright © 2024 Dan Jones <danjones@goodevilgenius.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cli
import (
"fmt"
"os"
fp "path/filepath"
"codeberg.org/danjones000/my-log/config"
"github.com/pelletier/go-toml/v2"
"github.com/spf13/cobra"
)
var ConfigCmd = &cobra.Command{
Use: "config",
Short: "Save default config to file, or print the current config value",
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) (err error) {
print, _ := cmd.Flags().GetBool("print")
if print {
fmt.Fprintln(cmd.OutOrStdout(), config.DefaultPath())
return nil
}
if len(args) > 0 {
v, _ := config.RetrieveFromContext(cmd.Context())
val := v.Get(args[0])
var out []byte
if val == nil {
out = []byte("<nil>")
} else {
var err error
out, err = toml.Marshal(val)
if err != nil {
return err
}
}
fmt.Fprintln(cmd.OutOrStdout(), string(out))
return nil
}
force, _ := cmd.Flags().GetBool("force")
configPath := config.DefaultPath()
if !force {
_, err = os.Stat(configPath)
if !os.IsNotExist(err) {
return fmt.Errorf("%s already exists. Use -f to overwrite", configPath)
}
}
dir := fp.Dir(configPath)
err = os.MkdirAll(dir, 0755)
if err != nil {
return
}
f, err := os.Create(configPath)
if err != nil {
return
}
defer f.Close()
c := config.DefaultStr()
fmt.Fprint(f, c)
return
},
}
func init() {
RootCmd.AddCommand(ConfigCmd)
ConfigCmd.Flags().BoolP("force", "f", false, "Force overwrite")
ConfigCmd.Flags().BoolP("print", "p", false, "Print path only")
}

View file

@ -1,133 +0,0 @@
/*
Copyright © 2024 Dan Jones <danjones@goodevilgenius.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cli
import (
"encoding/json"
"fmt"
"time"
"codeberg.org/danjones000/my-log/config"
"codeberg.org/danjones000/my-log/files"
"codeberg.org/danjones000/my-log/formatters"
"codeberg.org/danjones000/my-log/models"
"codeberg.org/danjones000/my-log/tools"
"github.com/spf13/cobra"
)
var d Date
var fields map[string]string
var j Json
var outJson bool
// DropCmd represents the drop command
var DropCmd = &cobra.Command{
Use: "drop log title",
Short: "Add a new log entry",
// Long: ``,
Args: cobra.ExactArgs(2),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
v, _ := config.RetrieveFromContext(cmd.Context())
if outJson {
v.Set("formatters.preferred", "json")
}
log := args[0]
title := args[1]
ms := &models.Metas{}
if len(j.RawMessage) > 8 {
err := json.Unmarshal([]byte(j.RawMessage), ms)
if err != nil {
return err
}
}
for k, v := range fields {
ms.AppendTo(k, tools.ParseString(v))
}
e := models.Entry{Title: title, Date: d.Time(), Fields: *ms}
l := models.Log{Name: log, Entries: []models.Entry{e}}
err := files.Append(cmd.Context(), l)
if err != nil {
return err
}
form, err := formatters.Preferred(cmd.Context())
if err != nil {
return err
}
out, err := form.Log(l)
if err != nil {
return err
}
if len(out) > 0 && out[len(out)-1] != 10 {
out = append(out, 10)
}
fmt.Fprintf(cmd.OutOrStdout(), "%s", out)
return nil
},
}
func init() {
RootCmd.AddCommand(DropCmd)
(&d).Set("now")
DropCmd.Flags().VarP(&d, "date", "d", "Date for log entry")
DropCmd.Flags().StringToStringVarP(&fields, "fields", "f", nil, "Fields you add to entry")
DropCmd.Flags().VarP(&j, "json", "j", "Entire entry as json")
DropCmd.Flags().BoolVarP(&outJson, "output_json", "o", false, "Output result as JSON")
}
type Json struct {
json.RawMessage
}
func (j *Json) String() string {
return string(j.RawMessage)
}
func (j *Json) Set(in string) error {
return json.Unmarshal([]byte(in), &j.RawMessage)
}
func (j *Json) Type() string {
return "json"
}
type Date struct {
s string
t time.Time
}
func (d *Date) String() string {
return d.s
}
func (d *Date) Set(in string) (err error) {
d.s = in
d.t, err = tools.ParseDate(in)
return
}
func (d *Date) Type() string {
return "datetime"
}
func (d Date) Time() time.Time {
return d.t
}

View file

@ -1,64 +0,0 @@
/*
Copyright © 2026 Dan Jones <danjones@goodevilgenius.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cli
import (
"context"
"os"
"codeberg.org/danjones000/my-log/config"
"github.com/spf13/cobra"
)
var RootCmd = &cobra.Command{
Use: "my-log",
Short: "A brief description of your application",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
ctx, v, err := config.New(cmd.Context(), configPath)
if err != nil {
return err
}
for k, val := range configValues {
v.Set(k, val)
}
cmd.SetContext(ctx)
return nil
},
}
func Execute(ctx context.Context) {
err := RootCmd.ExecuteContext(ctx)
if err != nil {
os.Exit(1)
}
}
var configPath string
var configValues map[string]string
func init() {
path := os.Getenv("MYLOG_CONFIG_PATH")
if path == "" {
path = config.DefaultPath()
}
RootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", path, "config file")
RootCmd.PersistentFlags().StringToStringVarP(&configValues, "config-value", "v", nil, "Override config values. Use dot syntax to specify key. E.g. -v formatters.preferred=json")
}

69
cli/ytdrop.go Normal file
View file

@ -0,0 +1,69 @@
/*
Copyright © 2026 Dan Jones <danjones@goodevilgenius.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cli
import (
"fmt"
"my-log-wynter/ytdlp"
mycli "codeberg.org/danjones000/my-log/cli"
"codeberg.org/danjones000/my-log/config"
"codeberg.org/danjones000/my-log/formatters"
"github.com/spf13/cobra"
)
var outJson bool
// YtDropCmd represents the drop command
var YtDropCmd = &cobra.Command{
Use: "drop:yt url",
Short: "Add a new YouTube video to the watched log",
// Long: ``,
Args: cobra.ExactArgs(1),
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
if outJson {
config.Overrides["output.stdout.config.format"] = "json"
}
url := args[0]
log, err := ytdlp.Drop(cmd.Context(), url)
if err != nil {
return err
}
form, err := formatters.Preferred()
if err != nil {
return err
}
out, err := form.Log(log)
if err != nil {
return err
}
if len(out) > 0 && out[len(out)-1] != 10 {
out = append(out, 10)
}
fmt.Fprintf(cmd.OutOrStdout(), "%s", out)
return nil
},
}
func init() {
mycli.RootCmd.AddCommand(YtDropCmd)
YtDropCmd.Flags().BoolVarP(&outJson, "output_json", "o", false, "Output result as JSON")
}

View file

@ -1,5 +1,5 @@
/*
Copyright © 2026 Dan Jones <danjones@goodevilgenius.org>
Copyright © 2024 Dan Jones <danjones@goodevilgenius.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
@ -17,11 +17,11 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"context"
_ "my-log-wynter/cli"
"codeberg.org/danjones000/my-log/cli"
mylog "codeberg.org/danjones000/my-log/cli"
)
func main() {
cli.Execute(context.Background())
mylog.Execute()
}

View file

@ -1,52 +0,0 @@
package config
import (
"fmt"
"os"
fp "path/filepath"
)
const ConfigStr = `# Configuration for my-log
[input]
# Path to where the log files are stored
path = "%s"
# File extension for log files
ext = "txt"
# Whether to look in sub-folders
recurse = true
# Whether to use a dot as a folder separator in log names
dotFolder = true
# config for output types
[output]
# This one just prints the logs to stdout when run
[output.stdout]
enabled = true
[output.stdout.config]
# Formatter to use when outputting to stdout
format = "plain"
[formatters]
# Default formatter used. Some outputs can override this value
preferred = "plain"
# Each formatter may have additional configuration
[formatters.json]
# Set to true to pretty print JSON output
pretty_print = false
`
func DefaultPath() string {
conf, _ := os.UserConfigDir()
return fp.Join(conf, "my-log", "config.toml")
}
func DefaultStr() string {
home, _ := os.UserHomeDir()
inDir := fp.Join(home, "my-log")
return fmt.Sprintf(ConfigStr, inDir)
}

View file

@ -1,57 +0,0 @@
package config
import (
"bytes"
"context"
"fmt"
"strings"
"github.com/spf13/viper"
)
type confKeyType uint8
const (
_ confKeyType = iota
viperKey
)
func RetrieveFromContext(ctx context.Context) (*viper.Viper, Config) {
v, ok := ctx.Value(viperKey).(*viper.Viper)
if !ok {
panic("config not found in context")
}
var c Config
if err := v.Unmarshal(&c); err != nil {
panic(fmt.Errorf("failed to unmarshal config: %w", err))
}
return v, c
}
func AddToContext(ctx context.Context, v *viper.Viper) context.Context {
return context.WithValue(ctx, viperKey, v)
}
func New(ctx context.Context, path string) (context.Context, *viper.Viper, error) {
v := viper.New()
v.SetConfigType("toml")
if err := v.ReadConfig(bytes.NewBufferString(DefaultStr())); err != nil {
return ctx, nil, err
}
if path == "" {
path = DefaultPath()
}
v.SetConfigFile(path)
v.SetEnvPrefix("MYLOG")
v.AutomaticEnv()
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
if err := v.MergeInConfig(); err != nil {
return ctx, nil, err
}
return AddToContext(ctx, v), v, nil
}

View file

@ -1,48 +0,0 @@
package config
import (
"os"
"testing"
"github.com/nalgeon/be"
"github.com/spf13/viper"
)
func TestNew(t *testing.T) {
_, v, err := New(t.Context(), "")
be.Err(t, err, nil)
be.True(t, v != nil)
}
func TestNewWithEnvOverrides(t *testing.T) {
os.Setenv("MYLOG_INPUT_PATH", "/test/path")
defer os.Unsetenv("MYLOG_INPUT_PATH")
_, v, err := New(t.Context(), "")
be.Err(t, err, nil)
be.Equal(t, v.GetString("input.path"), "/test/path")
}
func TestNewWithConfigFile(t *testing.T) {
dir := t.ArtifactDir()
f, _ := os.CreateTemp(dir, "test*.toml")
defer os.Remove(f.Name())
f.WriteString(`[input]
path = "/file/path"
ext = "log"`)
f.Close()
_, v, err := New(t.Context(), f.Name())
be.Err(t, err, nil)
be.Err(t, err, nil)
be.Equal(t, v.GetString("input.path"), "/file/path")
be.Equal(t, v.GetString("input.ext"), "log")
}
func TestRetrieveFromContext(t *testing.T) {
v := viper.New()
ctx := AddToContext(t.Context(), v)
result, _ := RetrieveFromContext(ctx)
be.True(t, v == result)
}

View file

@ -1,25 +0,0 @@
package config
type Config struct {
Input Input
Outputs Outputs `mapstructure:"output"`
Formatters Formatters
}
type Input struct {
Path string
Recurse bool
Ext string
DotFolder bool `mapstructure:"dotFolder"`
}
type Outputs map[string]Output
type Output struct {
Enabled bool
Config map[string]any
}
type Formatters struct {
Preferred string
}

View file

@ -1,62 +0,0 @@
package files
import (
"context"
"fmt"
"io"
"os"
fp "path/filepath"
"strings"
"codeberg.org/danjones000/my-log/config"
"codeberg.org/danjones000/my-log/models"
)
func Append(ctx context.Context, l models.Log) error {
_, conf := config.RetrieveFromContext(ctx)
filename := l.Name
if conf.Input.DotFolder {
filename = strings.ReplaceAll(filename, ".", string(os.PathSeparator))
}
if conf.Input.Ext != "" {
filename = fmt.Sprintf("%s.%s", filename, conf.Input.Ext)
}
path := fp.Join(conf.Input.Path, filename)
dir := fp.Dir(path)
err := os.MkdirAll(dir, 0750)
if err != nil {
return err
}
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0640)
if err != nil {
return err
}
defer f.Close()
f.Seek(-1, os.SEEK_END)
last := make([]byte, 1, 1)
n, err := f.Read(last)
if err != nil && err != io.EOF {
return err
}
if err == nil && n > 0 {
if last[0] != 10 {
f.Write([]byte{10})
}
}
for _, e := range l.Entries {
by, err := e.MarshalText()
if err != nil {
continue
}
f.Write(by)
f.Write([]byte{10})
}
return nil
}

View file

@ -1,236 +0,0 @@
package files
import (
"context"
"fmt"
"os"
"strings"
"testing"
"time"
"codeberg.org/danjones000/my-log/config"
"codeberg.org/danjones000/my-log/models"
"github.com/nalgeon/be"
"github.com/spf13/viper"
)
func TestAppend(tt *testing.T) {
tt.Run("success", func(t *testing.T) {
t.Run("single", appendTestSingle)
t.Run("two", appendTestTwoEntries)
t.Run("new_line", appendTestAddNewLine)
t.Run("no-new-line", appendTestDontAddNewLine)
t.Run("dot-folder", appendTestDotFolder)
t.Run("no-dot-folder", appendTestDotFolderNo)
t.Run("no-ext", appendTestNoExt)
})
tt.Run("failure", func(t *testing.T) {
t.Run("badEntry", appendTestBadEntry)
t.Run("mkdir-err", appendTestMkdirErr)
t.Run("append-log-err", appendTestOpenErr)
})
}
func setupAppendTest(t *testing.T) (string, context.Context) {
t.Helper()
dir := t.ArtifactDir()
v := viper.New()
v.SetConfigType("toml")
v.Set("input.path", dir)
v.Set("input.ext", "log")
v.Set("input.dotFolder", false)
ctx := config.AddToContext(t.Context(), v)
return dir, ctx
}
func appendTestSingle(t *testing.T) {
dir, ctx := setupAppendTest(t)
when := time.Now().Local()
e := models.Entry{
Title: "Jimmy",
Date: when,
Fields: []models.Meta{
{Key: "foo", Value: 42},
{Key: "bar", Value: true},
},
}
l := models.Log{
Name: "test",
Entries: []models.Entry{e},
}
err := Append(ctx, l)
be.Err(t, err, nil)
by, err := os.ReadFile(dir + "/test.log")
be.Err(t, err, nil)
st := string(by)
be.True(t, strings.Contains(st, "Jimmy\n"))
be.True(t, strings.Contains(st, "\n@foo 42"))
be.True(t, strings.Contains(st, "\n@bar true"))
}
func appendTestTwoEntries(t *testing.T) {
dir, ctx := setupAppendTest(t)
when := time.Now().Local()
whens := when.Format(models.DateFormat)
e := []models.Entry{
{Title: "one", Date: when},
{Title: "two", Date: when},
}
l := models.Log{
Name: "test",
Entries: e,
}
err := Append(ctx, l)
be.Err(t, err, nil)
by, _ := os.ReadFile(dir + "/test.log")
st := string(by)
be.True(t, strings.Contains(st, fmt.Sprintf("@begin %s - one", whens)))
be.True(t, strings.Contains(st, fmt.Sprintf("@begin %s - two", whens)))
}
func appendTestAddNewLine(t *testing.T) {
dir, ctx := setupAppendTest(t)
os.WriteFile(dir+"/test.log", []byte("foo"), 0644)
when := time.Now().Local()
whens := when.Format(models.DateFormat)
e := []models.Entry{
{Title: "one", Date: when, Fields: models.Metas{{Key: "id", Value: "jimmy"}}},
}
l := models.Log{
Name: "test",
Entries: e,
}
err := Append(ctx, l)
be.Err(t, err, nil)
by, _ := os.ReadFile(dir + "/test.log")
exp := fmt.Sprintf("foo\n@begin %s - one\n@id jimmy @end\n", whens)
be.Equal(t, string(by), exp)
}
func appendTestDontAddNewLine(t *testing.T) {
dir, ctx := setupAppendTest(t)
os.WriteFile(dir+"/test.log", []byte("foo\n"), 0644)
when := time.Now().Local()
whens := when.Format(models.DateFormat)
e := []models.Entry{
{Title: "one", Date: when, Fields: models.Metas{{Key: "id", Value: "jimmy"}}},
}
l := models.Log{
Name: "test",
Entries: e,
}
err := Append(ctx, l)
be.Err(t, err, nil)
by, _ := os.ReadFile(dir + "/test.log")
exp := fmt.Sprintf("foo\n@begin %s - one\n@id jimmy @end\n", whens)
be.Equal(t, string(by), exp)
}
func appendTestBadEntry(t *testing.T) {
dir, ctx := setupAppendTest(t)
e := models.Entry{
Title: "Jimmy",
}
l := models.Log{
Name: "test",
Entries: []models.Entry{e},
}
err := Append(ctx, l)
be.Err(t, err, nil)
by, _ := os.ReadFile(dir + "/test.log")
be.Equal(t, by, []byte{})
}
func appendTestDotFolder(t *testing.T) {
dir := t.ArtifactDir()
v := viper.New()
v.SetConfigType("toml")
v.Set("input.path", dir)
v.Set("input.ext", "log")
v.Set("input.dotFolder", true)
ctx := config.AddToContext(t.Context(), v)
e := models.Entry{
Title: "something",
Date: time.Now(),
}
l := models.Log{
Name: "sub.test",
Entries: []models.Entry{e},
}
err := Append(ctx, l)
be.Err(t, err, nil)
by, err := os.ReadFile(dir + "/sub/test.log")
be.Err(t, err, nil)
st := string(by)
be.True(t, strings.Contains(st, fmt.Sprintf("@begin %s - %s", e.Date.Format(models.DateFormat), e.Title)))
}
func appendTestDotFolderNo(t *testing.T) {
dir, ctx := setupAppendTest(t)
e := models.Entry{
Title: "another",
Date: time.Now(),
}
l := models.Log{
Name: "sub.test",
Entries: []models.Entry{e},
}
err := Append(ctx, l)
be.Err(t, err, nil)
by, err := os.ReadFile(dir + "/sub.test.log")
be.Err(t, err, nil)
st := string(by)
be.True(t, strings.Contains(st, fmt.Sprintf("@begin %s - %s", e.Date.Format(models.DateFormat), e.Title)))
}
func appendTestNoExt(t *testing.T) {
dir := t.ArtifactDir()
v := viper.New()
v.SetConfigType("toml")
v.Set("input.path", dir)
v.Set("input.ext", "")
v.Set("input.dotFolder", false)
ctx := config.AddToContext(t.Context(), v)
e := models.Entry{
Title: "baz",
Date: time.Now(),
}
l := models.Log{
Name: "foobar",
Entries: []models.Entry{e},
}
err := Append(ctx, l)
be.Err(t, err, nil)
by, err := os.ReadFile(dir + "/foobar")
be.Err(t, err, nil)
st := string(by)
be.True(t, strings.Contains(st, fmt.Sprintf("@begin %s - %s", e.Date.Format(models.DateFormat), e.Title)))
}
func appendTestMkdirErr(t *testing.T) {
v := viper.New()
v.SetConfigType("toml")
v.Set("input.path", "/var/my-logs-test")
v.Set("input.ext", "log")
v.Set("input.dotFolder", false)
ctx := config.AddToContext(t.Context(), v)
err := Append(ctx, models.Log{})
be.Err(t, err, "permission denied")
}
func appendTestOpenErr(t *testing.T) {
dir, ctx := setupAppendTest(t)
l := models.Log{
Name: "test-open-err",
}
fname := dir + "/test-open-err.log"
os.MkdirAll(dir, 0750)
f, _ := os.Create(fname)
f.Close()
os.Chmod(fname, 0400)
err := Append(ctx, l)
be.Err(t, err, "permission denied")
}

View file

@ -1,11 +0,0 @@
package formatters
import "codeberg.org/danjones000/my-log/models"
type Formatter interface {
Name() string
Logs([]models.Log) (out []byte, err error)
Log(models.Log) (out []byte, err error)
Entry(models.Entry) (out []byte, err error)
Meta(models.Meta) (out []byte, err error)
}

View file

@ -1,85 +0,0 @@
package formatters
import (
"bytes"
"encoding/json"
"fmt"
"time"
"codeberg.org/danjones000/my-log/models"
"github.com/spf13/viper"
)
const FormatJSON string = "json"
func newJson(ff *viper.Viper) (Formatter, error) {
js := new(Json)
err := ff.Unmarshal(js)
if err != nil {
return nil, fmt.Errorf("failed to get json config: %w", err)
}
return js, nil
}
type Json struct {
prettPrint bool `mapstructure:"pretty_print"`
}
func (js *Json) Name() string {
return FormatJSON
}
func (js *Json) marshal(v any) (o []byte, err error) {
o, err = json.Marshal(v)
if err != nil {
return
}
if js.prettPrint {
buff := &bytes.Buffer{}
err = json.Indent(buff, o, "", "\t")
if err == nil {
o = buff.Bytes()
}
}
return
}
func (js *Json) Meta(m models.Meta) ([]byte, error) {
o := map[string]any{m.Key: m.Value}
return js.marshal(o)
}
func (js *Json) entryMap(e models.Entry) map[string]any {
o := map[string]any{
"title": e.Title,
"date": e.Date.Format(time.RFC3339),
}
for _, m := range e.Fields {
o[m.Key] = m.Value
}
return o
}
func (js *Json) Entry(e models.Entry) ([]byte, error) {
return js.marshal(js.entryMap(e))
}
func (js *Json) Log(l models.Log) ([]byte, error) {
return js.Logs([]models.Log{l})
}
func (js *Json) Logs(logs []models.Log) (out []byte, err error) {
if len(logs) == 0 {
return
}
o := map[string][]map[string]any{}
for _, l := range logs {
es := []map[string]any{}
for _, e := range l.Entries {
es = append(es, js.entryMap(e))
}
o[l.Name] = es
}
return js.marshal(o)
}

View file

@ -1,99 +0,0 @@
package formatters
import (
"context"
"fmt"
"testing"
"time"
"codeberg.org/danjones000/my-log/config"
"codeberg.org/danjones000/my-log/internal/testutil/bep"
"codeberg.org/danjones000/my-log/models"
"github.com/nalgeon/be"
"github.com/spf13/viper"
)
func setupJsonTestContext(t *testing.T) context.Context {
t.Helper()
v := viper.New()
v.SetConfigType("toml")
v.Set("formatters.json.pretty_print", false)
return config.AddToContext(t.Context(), v)
}
func TestJsonName(t *testing.T) {
ctx := setupJsonTestContext(t)
f, _ := New(ctx, "json")
be.Equal(t, f.Name(), "json")
}
func TestJsonMeta(t *testing.T) {
ctx := setupJsonTestContext(t)
f, _ := New(ctx, "json")
m := models.Meta{Key: "foo", Value: 42}
exp := `{"foo":42}`
o, err := f.Meta(m)
be.Err(t, err, nil)
bep.JSON(t, o, []byte(exp))
}
func TestJsonEntry(t *testing.T) {
ctx := setupJsonTestContext(t)
when := time.Now()
f, _ := New(ctx, "json")
m := models.Meta{Key: "foo", Value: 42}
e := models.Entry{
Title: "Homer",
Date: when,
Fields: []models.Meta{m},
}
exp := fmt.Sprintf(`{"title":"%s","date":"%s","foo":42}`, e.Title, when.Format(time.RFC3339))
o, err := f.Entry(e)
be.Err(t, err, nil)
bep.JSON(t, o, []byte(exp))
}
func TestJsonLog(t *testing.T) {
ctx := setupJsonTestContext(t)
when := time.Now()
f, _ := New(ctx, "json")
m := models.Meta{Key: "foo", Value: 42}
e := models.Entry{
Title: "Homer",
Date: when,
Fields: []models.Meta{m},
}
l := models.Log{Name: "stuff", Entries: []models.Entry{e}}
exp := fmt.Sprintf(`{"%s":[{"title":"%s","date":"%s","foo":42}]}`, l.Name, e.Title, when.Format(time.RFC3339))
o, err := f.Log(l)
be.Err(t, err, nil)
bep.JSON(t, o, []byte(exp))
}
func TestJsonNoLogs(t *testing.T) {
ctx := setupJsonTestContext(t)
f, _ := New(ctx, "json")
o, err := f.Logs([]models.Log{})
var exp []byte
be.Err(t, err, nil)
be.Equal(t, o, exp)
}
func TestJsonErr(t *testing.T) {
ctx := setupJsonTestContext(t)
f, _ := New(ctx, "json")
o, err := f.Meta(models.Meta{Key: "foo", Value: make(chan bool)})
var exp []byte
be.Err(t, err)
be.Equal(t, o, exp)
}
func TestJsonPretty(t *testing.T) {
f := Json{true}
o, err := f.Meta(models.Meta{Key: "foo", Value: 42})
exp := `{
"foo": 42
}`
be.Err(t, err, nil)
be.Equal(t, string(o), exp)
}

View file

@ -1,63 +0,0 @@
package formatters
import (
"context"
"errors"
"fmt"
"sync"
"codeberg.org/danjones000/my-log/config"
"github.com/spf13/viper"
)
var mut sync.RWMutex
type FormatInit func(config *viper.Viper) (Formatter, error)
var formatterMap = map[string]FormatInit{
FormatPlain: newPlain,
FormatJSON: newJson,
FormatNull: newNull,
}
func Preferred(ctx context.Context) (f Formatter, err error) {
_, c := config.RetrieveFromContext(ctx)
return New(ctx, c.Formatters.Preferred)
}
func New(ctx context.Context, kind string) (f Formatter, err error) {
v, _ := config.RetrieveFromContext(ctx)
formatterConf := v.Sub("formatters." + kind)
mut.RLock()
defer mut.RUnlock()
if maker, ok := formatterMap[kind]; ok {
return maker(formatterConf)
}
return nil, fmt.Errorf("unimplemented format: %s", kind)
}
func Kinds() []string {
r := []string{}
mut.RLock()
defer mut.RUnlock()
for kind, _ := range formatterMap {
r = append(r, kind)
}
return r
}
var ErrAlreadyAdded = errors.New("formatter already present")
func AddFormatter(key string, f FormatInit) error {
mut.Lock()
defer mut.Unlock()
if _, present := formatterMap[key]; present {
return fmt.Errorf("%w: %s", ErrAlreadyAdded, key)
}
formatterMap[key] = f
return nil
}

View file

@ -1,55 +0,0 @@
package formatters
import (
"context"
"slices"
"testing"
"codeberg.org/danjones000/my-log/config"
"github.com/nalgeon/be"
"github.com/spf13/viper"
)
func TestKinds(t *testing.T) {
kinds := Kinds()
for _, kind := range []string{"plain", "json", "zero"} {
be.True(t, slices.Contains(kinds, kind))
}
}
func setupNewTest(t *testing.T) context.Context {
t.Helper()
v := viper.New()
v.SetConfigType("toml")
v.Set("formatters.preferred", "plain")
v.Set("formatters.json.pretty_print", false)
return config.AddToContext(t.Context(), v)
}
func TestNewUnsupported(t *testing.T) {
ctx := setupNewTest(t)
f, err := New(ctx, "nope")
be.Equal(t, f, nil)
be.Err(t, err)
}
func TestPreferred(t *testing.T) {
ctx := setupNewTest(t)
form, err := Preferred(ctx)
be.Err(t, err, nil)
be.True(t, form != nil)
}
type dummyFormatter struct{ Null }
func (dummyFormatter) Name() string { return "dummy" }
func TestAddFormatter(t *testing.T) {
var df dummyFormatter
dummyInit := func(*viper.Viper) (Formatter, error) { return df, nil }
err := AddFormatter(df.Name(), dummyInit)
be.Err(t, err, nil)
err = AddFormatter(df.Name(), dummyInit)
be.Err(t, err, ErrAlreadyAdded)
}

View file

@ -1,23 +0,0 @@
package formatters
import (
"codeberg.org/danjones000/my-log/models"
"github.com/spf13/viper"
)
const FormatNull = "zero"
func newNull(*viper.Viper) (Formatter, error) {
return Null{}, nil
}
type Null struct{}
func (Null) Name() string {
return FormatNull
}
func (Null) Meta(m models.Meta) (o []byte, err error) { return }
func (Null) Entry(e models.Entry) (o []byte, err error) { return }
func (Null) Log(l models.Log) (o []byte, err error) { return }
func (Null) Logs(logs []models.Log) (out []byte, err error) { return }

View file

@ -1,60 +0,0 @@
package formatters
import (
"context"
"testing"
"time"
"codeberg.org/danjones000/my-log/config"
"codeberg.org/danjones000/my-log/models"
"github.com/nalgeon/be"
"github.com/spf13/viper"
)
var empty []byte
func setupNullTestContext(t *testing.T) context.Context {
t.Helper()
v := viper.New()
v.SetConfigType("toml")
return config.AddToContext(t.Context(), v)
}
func TestNullName(t *testing.T) {
ctx := setupNullTestContext(t)
f, err := New(ctx, "zero")
be.Err(t, err, nil)
be.Equal(t, f.Name(), "zero")
}
func TestNullMeta(t *testing.T) {
ctx := setupNullTestContext(t)
f, _ := New(ctx, "zero")
o, err := f.Meta(models.Meta{Key: "foo", Value: 42})
be.Err(t, err, nil)
be.Equal(t, o, empty)
}
func TestNullEntry(t *testing.T) {
ctx := setupNullTestContext(t)
f, _ := New(ctx, "zero")
o, err := f.Entry(models.Entry{Title: "title", Date: time.Now()})
be.Err(t, err, nil)
be.Equal(t, o, empty)
}
func TestNullLog(t *testing.T) {
ctx := setupNullTestContext(t)
f, _ := New(ctx, "zero")
o, err := f.Log(models.Log{Name: "jim", Entries: []models.Entry{{Title: "title", Date: time.Now()}}})
be.Err(t, err, nil)
be.Equal(t, o, empty)
}
func TestNullLogs(t *testing.T) {
ctx := setupNullTestContext(t)
f, _ := New(ctx, "zero")
o, err := f.Logs([]models.Log{{Name: "jim", Entries: []models.Entry{{Title: "title", Date: time.Now()}}}})
be.Err(t, err, nil)
be.Equal(t, o, empty)
}

View file

@ -1,108 +0,0 @@
package formatters
import (
"bytes"
"codeberg.org/danjones000/my-log/models"
"codeberg.org/danjones000/my-log/tools"
"github.com/spf13/viper"
)
const FormatPlain string = "plain"
func newPlain(*viper.Viper) (Formatter, error) {
return &PlainText{}, nil
}
type PlainText struct{}
func (*PlainText) Name() string {
return FormatPlain
}
func (pt *PlainText) Logs(logs []models.Log) (out []byte, err error) {
if len(logs) == 0 {
return
}
buff := &bytes.Buffer{}
first := true
for _, log := range logs {
o, _ := pt.Log(log)
if !first {
buff.WriteByte(10)
buff.WriteByte(10)
}
first = false
buff.Write(o)
}
out = buff.Bytes()
return
}
func (pt *PlainText) Log(log models.Log) (out []byte, err error) {
if len(log.Entries) == 0 {
return
}
buff := &bytes.Buffer{}
buff.WriteString(log.Name)
buff.WriteString("\n#######")
written := false
for _, e := range log.Entries {
bb := pt.entryBuffer(e)
if bb.Len() > 0 {
buff.WriteByte(10)
buff.WriteByte(10)
buff.ReadFrom(bb)
written = true
}
}
if written {
out = buff.Bytes()
}
return
}
func (pt *PlainText) entryBuffer(entry models.Entry) *bytes.Buffer {
buff := &bytes.Buffer{}
buff.WriteString("Title: ")
buff.WriteString(entry.Title)
buff.WriteByte(10)
buff.WriteString("Date: ")
buff.WriteString(entry.Date.Format(tools.DateFormat))
for _, m := range entry.Fields {
bb, err := pt.metaBuffer(m)
if (bb.Len() > 0) && (err == nil) {
buff.WriteByte(10)
buff.ReadFrom(bb)
}
}
return buff
}
func (pt *PlainText) Entry(entry models.Entry) ([]byte, error) {
buff := pt.entryBuffer(entry)
return buff.Bytes(), nil
}
func (pt *PlainText) metaBuffer(meta models.Meta) (*bytes.Buffer, error) {
buff := &bytes.Buffer{}
buff.WriteString(meta.Key)
buff.WriteString(": ")
n, err := tools.WriteValue(buff, meta.Value)
if n == 0 || err != nil {
return &bytes.Buffer{}, err
}
return buff, nil
}
func (pt *PlainText) Meta(meta models.Meta) (out []byte, err error) {
buff, err := pt.metaBuffer(meta)
if err != nil {
return
}
out = buff.Bytes()
return
}

View file

@ -1,156 +0,0 @@
package formatters
import (
"bufio"
"bytes"
"context"
"fmt"
"testing"
"time"
"codeberg.org/danjones000/my-log/config"
"codeberg.org/danjones000/my-log/models"
"codeberg.org/danjones000/my-log/tools"
"github.com/nalgeon/be"
"github.com/spf13/viper"
)
func setupPlainTestContext(t *testing.T) context.Context {
t.Helper()
v := viper.New()
v.SetConfigType("toml")
return config.AddToContext(t.Context(), v)
}
func TestPlainLogs(t *testing.T) {
ctx := setupPlainTestContext(t)
m := []models.Meta{
{Key: "foo", Value: "bar"},
{Key: "baz", Value: 42},
}
e := []models.Entry{
{Title: "one", Date: time.Now(), Fields: m},
{Title: "small", Date: time.Now()},
}
l := models.Log{Name: "stuff", Entries: e}
e2 := models.Entry{
Title: "three",
Date: time.Now(),
}
l2 := models.Log{Name: "more-stuff", Entries: []models.Entry{e2}}
logs := []models.Log{l, l2}
f, err := New(ctx, "plain")
be.Err(t, err, nil)
out, err := f.Logs(logs)
be.Err(t, err, nil)
read := bytes.NewReader(out)
scan := bufio.NewScanner(read)
scan.Scan()
line := scan.Text()
be.Equal(t, line, l.Name)
scan.Scan()
line = scan.Text()
be.Equal(t, line, "#######")
scan.Scan()
scan.Scan()
line = scan.Text()
be.Equal(t, line, "Title: "+e[0].Title)
scan.Scan()
line = scan.Text()
be.Equal(t, line, "Date: "+e[0].Date.Format(tools.DateFormat))
scan.Scan()
line = scan.Text()
be.Equal(t, line, "foo: bar")
scan.Scan()
line = scan.Text()
be.Equal(t, line, "baz: 42")
scan.Scan()
scan.Scan()
line = scan.Text()
be.Equal(t, line, "Title: "+e[1].Title)
scan.Scan()
line = scan.Text()
be.Equal(t, line, "Date: "+e[1].Date.Format(tools.DateFormat))
scan.Scan()
scan.Scan()
line = scan.Text()
be.Equal(t, line, l2.Name)
scan.Scan()
line = scan.Text()
be.Equal(t, line, "#######")
scan.Scan()
scan.Scan()
line = scan.Text()
be.Equal(t, line, "Title: "+e2.Title)
scan.Scan()
line = scan.Text()
be.Equal(t, line, "Date: "+e2.Date.Format(tools.DateFormat))
more := scan.Scan()
be.True(t, !more)
}
func TestPlainName(t *testing.T) {
ctx := setupPlainTestContext(t)
f, _ := New(ctx, "plain")
be.Equal(t, f.Name(), "plain")
}
func TestPlainLogNone(t *testing.T) {
ctx := setupPlainTestContext(t)
f, _ := New(ctx, "plain")
out, err := f.Logs([]models.Log{})
be.Err(t, err, nil)
be.Equal(t, len(out), 0)
}
func TestPlainLogNoEntries(t *testing.T) {
ctx := setupPlainTestContext(t)
f, _ := New(ctx, "plain")
out, err := f.Log(models.Log{Name: "foo"})
be.Err(t, err, nil)
be.Equal(t, len(out), 0)
}
func TestPlainMetaEmpty(t *testing.T) {
ctx := setupPlainTestContext(t)
f, _ := New(ctx, "plain")
out, err := f.Meta(models.Meta{Key: "foo", Value: ""})
be.Err(t, err, nil)
be.Equal(t, len(out), 0)
}
func TestPlainMetaError(t *testing.T) {
ctx := setupPlainTestContext(t)
f, _ := New(ctx, "plain")
out, err := f.Meta(models.Meta{Key: "foo", Value: make(chan bool)})
be.Err(t, err)
be.Equal(t, len(out), 0)
}
func TestPlainEntry(t *testing.T) {
ctx := setupPlainTestContext(t)
f, _ := New(ctx, "plain")
now := time.Now()
out, err := f.Entry(models.Entry{
Title: "foo",
Date: now,
})
be.Err(t, err, nil)
be.Equal(t, string(out), fmt.Sprintf("Title: foo\nDate: %s", now.Format(tools.DateFormat)))
}

34
go.mod
View file

@ -1,35 +1,33 @@
module codeberg.org/danjones000/my-log
module my-log-wynter
go 1.26.0
require (
github.com/google/uuid v1.6.0
github.com/markusmobius/go-dateparser v1.2.3
github.com/nalgeon/be v0.3.0
github.com/spf13/cobra v1.8.0
github.com/spf13/viper v1.21.0
codeberg.org/danjones000/my-log v0.1.0
github.com/lrstanley/go-ytdlp v1.3.1
)
require (
github.com/BurntSushi/toml v1.3.2 // indirect
github.com/ProtonMail/go-crypto v1.3.0 // indirect
github.com/caarlos0/env/v10 v10.0.0 // indirect
github.com/cloudflare/circl v1.6.3 // indirect
github.com/elliotchance/pie/v2 v2.7.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hablullah/go-hijri v1.0.2 // indirect
github.com/hablullah/go-juliandays v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jalaali/go-jalaali v0.0.0-20210801064154-80525e88d958 // indirect
github.com/magefile/mage v1.14.0 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/markusmobius/go-dateparser v1.2.3 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/spf13/cobra v1.8.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/tetratelabs/wazero v1.2.1 // indirect
github.com/ulikunitz/xz v0.5.15 // indirect
github.com/wasilibs/go-re2 v1.3.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/crypto v0.48.0 // indirect
golang.org/x/exp v0.0.0-20220321173239-a90fa8a75705 // indirect
golang.org/x/sys v0.29.0 // indirect
golang.org/x/text v0.28.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.34.0 // indirect
)

61
go.sum
View file

@ -1,16 +1,18 @@
codeberg.org/danjones000/my-log v0.1.0 h1:HJYCZ8rYpOtVpU1927M1H1FjbB/6acwrV8eJ4TUDHac=
codeberg.org/danjones000/my-log v0.1.0/go.mod h1:XxiJfEyCKDeHzCNUeULL02zDXwsU2WHXfoBPNboYHYU=
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/ProtonMail/go-crypto v1.3.0 h1:ILq8+Sf5If5DCpHQp4PbZdS1J7HDFRXz/+xKBiRGFrw=
github.com/ProtonMail/go-crypto v1.3.0/go.mod h1:9whxjD8Rbs29b4XWbB8irEcE8KHMqaR2e7GWU1R+/PE=
github.com/caarlos0/env/v10 v10.0.0 h1:yIHUBZGsyqCnpTkbjk8asUlx6RFhhEs+h7TOBdgdzXA=
github.com/caarlos0/env/v10 v10.0.0/go.mod h1:ZfulV76NvVPw3tm591U4SwL3Xx9ldzBP9aGxzeN7G18=
github.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=
github.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/elliotchance/pie/v2 v2.7.0 h1:FqoIKg4uj0G/CrLGuMS9ejnFKa92lxE1dEgBD3pShXg=
github.com/elliotchance/pie/v2 v2.7.0/go.mod h1:18t0dgGFH006g4eVdDtWfgFZPQEgl10IoEO8YWEq3Og=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hablullah/go-hijri v1.0.2 h1:drT/MZpSZJQXo7jftf5fthArShcaMtsal0Zf/dnmp6k=
@ -21,58 +23,41 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jalaali/go-jalaali v0.0.0-20210801064154-80525e88d958 h1:qxLoi6CAcXVzjfvu+KXIXJOAsQB62LXjsfbOaErsVzE=
github.com/jalaali/go-jalaali v0.0.0-20210801064154-80525e88d958/go.mod h1:Wqfu7mjUHj9WDzSSPI5KfBclTTEnLveRUFr/ujWnTgE=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lrstanley/go-ytdlp v1.3.1 h1:zxhj0wstpfyAYz5ow7gHu/9QGEZtGhA2JX4/3Ym+bKo=
github.com/lrstanley/go-ytdlp v1.3.1/go.mod h1:VgjnTrvkTf+23JuySjyPq1iQ8ijSovBtTPpXH5XrLtI=
github.com/magefile/mage v1.14.0 h1:6QDX3g6z1YvJ4olPhT1wksUcSa/V0a1B+pJb73fBjyo=
github.com/magefile/mage v1.14.0/go.mod h1:z5UZb/iS3GoOSn0JgWuiw7dxlurVYTu+/jHXqQg881A=
github.com/markusmobius/go-dateparser v1.2.3 h1:TvrsIvr5uk+3v6poDjaicnAFJ5IgtFHgLiuMY2Eb7Nw=
github.com/markusmobius/go-dateparser v1.2.3/go.mod h1:cMwQRrBUQlK1UI5TIFHEcvpsMbkWrQLXuaPNMFzuYLk=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/nalgeon/be v0.3.0 h1:QsPANqEtcOD5qT2S3KAtIkDBBn8SXUf/Lb5Bi/z4UqM=
github.com/nalgeon/be v0.3.0/go.mod h1:PMwMuBLopwKJkSHnr2qHyLcZYUTqNejN7A8RAqNWO3E=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0=
github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/tetratelabs/wazero v1.2.1 h1:J4X2hrGzJvt+wqltuvcSjHQ7ujQxA9gb6PeMs4qlUWs=
github.com/tetratelabs/wazero v1.2.1/go.mod h1:wYx2gNRg8/WihJfSDxA1TIL8H+GkfLYm+bIfbblu9VQ=
github.com/ulikunitz/xz v0.5.15 h1:9DNdB5s+SgV3bQ2ApL10xRc35ck0DuIX/isZvIk+ubY=
github.com/ulikunitz/xz v0.5.15/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
github.com/wasilibs/go-re2 v1.3.0 h1:LFhBNzoStM3wMie6rN2slD1cuYH2CGiHpvNL3UtcsMw=
github.com/wasilibs/go-re2 v1.3.0/go.mod h1:AafrCXVvGRJJOImMajgJ2M7rVmWyisVK7sFshbxnVrg=
github.com/wasilibs/nottinygc v0.4.0 h1:h1TJMihMC4neN6Zq+WKpLxgd9xCFMw7O9ETLwY2exJQ=
github.com/wasilibs/nottinygc v0.4.0/go.mod h1:oDcIotskuYNMpqMF23l7Z8uzD4TC0WXHK8jetlB3HIo=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
golang.org/x/exp v0.0.0-20220321173239-a90fa8a75705 h1:ba9YlqfDGTTQ5aZ2fwOoQ1hf32QySyQkR6ODGDzHlnE=
golang.org/x/exp v0.0.0-20220321173239-a90fa8a75705/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE=
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View file

@ -1,21 +0,0 @@
package bep
import (
"encoding/json"
"testing"
"github.com/nalgeon/be"
)
func JSON(t *testing.T, got, want []byte) {
t.Helper()
var gotAny, wantAny any
err := json.Unmarshal(want, &wantAny)
be.Err(t, err, nil)
err = json.Unmarshal(got, &gotAny)
be.Err(t, err, nil)
be.Equal(t, gotAny, wantAny)
}

View file

@ -1,317 +0,0 @@
package models
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"maps"
"os"
"regexp"
"strings"
"sync"
"time"
"codeberg.org/danjones000/my-log/tools"
"github.com/google/uuid"
)
const DateFormat = tools.DateFormat
type Entry struct {
// ID is an optional, but recommended field.
// When marshaling/unmarshaling, if ID is empty, one is generated.
ID string
Title string
Date time.Time
Fields Metas
}
func GenerateID() string {
host, hostErr := os.Hostname()
if hostErr != nil {
host = "localhost"
}
return fmt.Sprintf(
"tag:%s,%s:my-log/%s",
host,
time.Now().Local().Format("2006"),
uuid.NewString(),
)
}
func EnsureID(id *string, fields Metas) {
if *id != "" {
return
}
metaID, hasMetaID := fields.Get("id")
var isStringID bool
*id, isStringID = metaID.(string)
if !hasMetaID || !isStringID {
*id = GenerateID()
}
}
type metaRes struct {
out []byte
err error
}
func getFieldMarshalChan(fields Metas) chan metaRes {
size := len(fields)
ch := make(chan metaRes, size)
var wg sync.WaitGroup
for i := range size {
wg.Add(1)
go func(m Meta) {
defer wg.Done()
if m.Key == "json" {
if j, ok := m.Value.(json.RawMessage); ok {
sub := Metas{}
json.Unmarshal(j, &sub)
for _, subM := range sub {
o, er := subM.MarshalText()
ch <- metaRes{o, er}
}
}
} else {
o, er := m.MarshalText()
ch <- metaRes{o, er}
}
}(fields[i])
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}
func (e Entry) MarshalText() ([]byte, error) {
e.Title = strings.TrimSpace(e.Title)
if e.Title == "" {
return []byte{}, ErrorMissingTitle
}
if e.Date.IsZero() {
return []byte{}, ErrorMissingDate
}
EnsureID(&e.ID, e.Fields)
fields := e.Fields.Set("id", e.ID)
ch := getFieldMarshalChan(fields)
buff := &bytes.Buffer{}
buff.WriteString("@begin ")
buff.WriteString(e.Date.Format(DateFormat))
buff.WriteString(" - ")
buff.WriteString(e.Title)
for res := range ch {
if res.err == nil && len(res.out) > 0 {
buff.WriteString("\n")
buff.Write(res.out)
}
}
buff.WriteString(" @end")
return buff.Bytes(), nil
}
func (m *Entry) UnmarshalText(in []byte) error {
re := regexp.MustCompile("(?s)^@begin (.+) - (.+?)[ \n]@")
match := re.FindSubmatch(in)
if len(match) == 0 {
return newParsingError(errors.New("Failed to find title and date"))
}
ch := m.getFieldUnarshalChan(in)
title := bytes.TrimSpace(match[2])
if len(title) == 0 {
return ErrorMissingTitle
}
m.Title = string(title)
date := string(bytes.TrimSpace(match[1]))
if date == "" {
return ErrorMissingDate
}
d, e := tools.ParseDate(date)
if e != nil {
return newParsingError(e)
}
m.Date = d
for meta := range ch {
if meta.Key == "id" {
if id, idIsString := meta.Value.(string); idIsString {
m.ID = id
}
}
m.Fields = append(m.Fields, meta)
}
EnsureID(&m.ID, m.Fields)
return nil
}
func scanEntry(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Index(data, []byte{10, 64}); i > 0 {
return i + 1, data[0:i], nil
}
if atEOF {
end := []byte{32, 64, 101, 110, 100}
token = data
if before, _, ok := bytes.Cut(data, end); ok {
token = before
}
return len(data), token, nil
}
// Request more data.
return 0, nil, nil
}
func (e *Entry) getFieldUnarshalChan(in []byte) chan Meta {
size := len(in) / 3 // rough estimation
ch := make(chan Meta, size)
var wg sync.WaitGroup
read := bytes.NewReader(in)
scan := bufio.NewScanner(read)
scan.Split(scanEntry)
scan.Scan() // throw out first line
for scan.Scan() {
wg.Add(1)
go func(field []byte) {
defer wg.Done()
m := new(Meta)
err := m.UnmarshalText(field)
if err == nil {
if m.Key == "json" {
if j, ok := m.Value.(json.RawMessage); ok {
ms := Metas{}
json.Unmarshal(j, &ms)
for _, subM := range ms {
ch <- subM
}
}
} else {
ch <- *m
}
}
}(scan.Bytes())
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}
func (e Entry) MarshalJSON() ([]byte, error) {
if e.Title == "" {
return []byte{}, ErrorMissingTitle
}
if e.Date == (time.Time{}) {
return []byte{}, ErrorMissingDate
}
EnsureID(&e.ID, e.Fields)
fields := e.Fields.Set("id", e.ID)
out := map[string]any{}
out["title"] = e.Title
out["date"] = e.Date.Format(time.RFC3339)
maps.Copy(out, fields.Map())
return json.Marshal(out)
}
func (e *Entry) unmarshalJsonChanHelper(m map[string]any, ch chan Meta, wg *sync.WaitGroup) {
for k, v := range m {
wg.Add(1)
go func(key string, value any) {
defer wg.Done()
if key != "json" {
ch <- Meta{key, value}
return
}
subM := map[string]any{}
if s, ok := value.(string); ok {
dec := json.NewDecoder(strings.NewReader(s))
dec.UseNumber()
dec.Decode(&subM)
} else {
subM = value.(map[string]any)
}
e.unmarshalJsonChanHelper(subM, ch, wg)
}(k, v)
}
}
func (e *Entry) getUnmarshalJsonChan(m map[string]any) chan Meta {
ch := make(chan Meta, len(m))
var wg sync.WaitGroup
e.unmarshalJsonChanHelper(m, ch, &wg)
go func() {
wg.Wait()
close(ch)
}()
return ch
}
func (e *Entry) UnmarshalJSON(in []byte) error {
out := map[string]any{}
dec := json.NewDecoder(bytes.NewReader(in))
dec.UseNumber()
err := dec.Decode(&out)
if err != nil {
return newParsingError(err)
}
title, ok := out["title"].(string)
if !ok || title == "" {
return ErrorMissingTitle
}
e.Title = title
dates, ok := out["date"].(string)
if !ok || dates == "" {
return ErrorMissingDate
}
date, err := tools.ParseDate(dates)
if err != nil {
return newParsingError(err)
}
e.Date = date
ch := e.getUnmarshalJsonChan(out)
for m := range ch {
if m.Key == "title" || m.Key == "date" {
continue
} else if vs, ok := m.Value.(string); ok {
if vd, err := tools.ParseDate(vs); err == nil {
m.Value = vd
} else {
m.Value = vs
}
} else if n, ok := m.Value.(json.Number); ok {
it, _ := n.Int64()
fl, _ := n.Float64()
if float64(it) == fl {
m.Value = it
} else {
m.Value = fl
}
}
e.Fields = append(e.Fields, m)
}
EnsureID(&e.ID, e.Fields)
return nil
}

View file

@ -1,655 +0,0 @@
package models
import (
"bufio"
"encoding"
"encoding/json"
"regexp"
"strings"
"testing"
"time"
"github.com/nalgeon/be"
)
// Type assertions
var _ encoding.TextMarshaler = Entry{}
var _ encoding.TextUnmarshaler = new(Entry)
var _ json.Marshaler = Entry{}
var _ json.Unmarshaler = new(Entry)
func TestEntryMarshal(t *testing.T) {
when := time.Now()
whens := when.Format(DateFormat)
simple := []Meta{}
nolines := []string{}
tests := []struct {
name string
title string
date time.Time
fields []Meta
first string
lines []string
err error
}{
{"no-title", "", when, simple, "", nolines, ErrorMissingTitle},
{"zero-date", "Empty title", time.Time{}, simple, "", nolines, ErrorMissingDate},
{"one-line", "A Title", when, simple, "@begin " + whens + " - A Title", []string{"@id .+ @end"}, nil},
{
"one-field",
"Title 2",
when,
[]Meta{{"age", 41}},
"@begin " + whens + " - Title 2",
[]string{"@age 41", "@id .*"},
nil,
},
{
"three-fields",
"Title 3",
when,
[]Meta{{"age", 41}, {"cool", true}, {"name", "Jim"}},
"@begin " + whens + " - Title 3",
[]string{"@age 41", "@cool true", "@name Jim"},
nil,
},
{
"json-field",
"Title J",
when,
[]Meta{{"json", json.RawMessage(`{"age": 41, "cool": true, "name": "Jim"}`)}},
"@begin " + whens + " - Title J",
[]string{"@age 41", "@cool true", "@name Jim"},
nil,
},
{
"nested-json",
"Title N",
when,
[]Meta{{"me", json.RawMessage(`{"age": 43, "cool": true}`)}},
"@begin " + whens + " - Title N",
[]string{"@me:age 43", "@me:cool true"},
nil,
},
{
"nested-map",
"Title M",
when,
[]Meta{{"me", map[string]any{"age": 43, "cool": true}}},
"@begin " + whens + " - Title M",
[]string{"@me:age 43", "@me:cool true"},
nil,
},
{
"double-nested-map",
"Title DM",
when,
[]Meta{{"me", map[string]any{"age": 43, "name": map[string]any{"first": "Dan", "last": "Jones"}}}},
"@begin " + whens + " - Title DM",
[]string{"@me:age 43", "@me:name:first Dan", "@me:name:last Jones"},
nil,
},
{
"double-nested-map-dot",
"Title DM",
when,
[]Meta{{"me", map[string]any{"age": 43, "name": map[string]any{".": "Dan Jones", "nick": "Danny"}}}},
"@begin " + whens + " - Title DM",
[]string{"@me:age 43", "@me:name Dan Jones", "@me:name:nick Danny"},
nil,
},
{
"double-nested-map-blank",
"Title DM",
when,
[]Meta{{"me", map[string]any{"age": 43, "name": map[string]any{"": "Dan Jones", "nick": "Danny"}}}},
"@begin " + whens + " - Title DM",
[]string{"@me:age 43", "@me:name Dan Jones", "@me:name:nick Danny"},
nil,
},
{
"nested-keys-in-json",
"Title NKJ",
when,
[]Meta{{"me", json.RawMessage(`{"name:first": "Dan", "name:last": "Jones"}`)}},
"@begin " + whens + " - Title NKJ",
[]string{"@me:name:first Dan", "@me:name:last Jones"},
nil,
},
}
for _, tt := range tests {
t.Run(tt.name, getEntryMarshalTestRunner(tt.title, tt.date, tt.fields, tt.first, tt.lines, tt.err))
}
}
func getEntryMarshalTestRunner(title string, date time.Time, fields []Meta, first string, lines []string, err error) func(*testing.T) {
return func(t *testing.T) {
en := Entry{Title: title, Date: date, Fields: fields}
o, er := en.MarshalText()
be.Err(t, er, err)
if first == "" {
return
}
os := string(o)
if len(lines) == 0 {
be.Equal(t, os, first)
return
}
be.True(t, regexp.MustCompile(first).MatchString(os))
for _, line := range lines {
be.True(t, regexp.MustCompile("(?m)^"+line).MatchString(os))
}
}
}
func TestEntryUnmarshal(t *testing.T) {
when := time.Now()
whens := when.Format(DateFormat)
simple := []Meta{}
tests := []struct {
name string
in string
title string
date time.Time
id string
fields []Meta
err error
}{
{"one-line", "@begin " + whens + " - A Title @end", "A Title", when, "", simple, nil},
{"with-id", "@begin " + whens + " - A Title\n@id jimmy-john @end", "A Title", when, "jimmy-john", simple, nil},
{"rfc3999-date", "@begin " + when.Format(time.RFC3339) + " - A Title @end", "A Title", when, "", simple, nil},
{"multi-title", "@begin " + whens + " - A Title\nwith break @end", "A Title\nwith break", when, "", simple, nil},
{"no-title", "@begin " + whens + " - @end", "", when, "", simple, ErrorMissingTitle},
{"parse-error", "this is no good", "", when, "", simple, ErrorParsing},
{"no-date", "@begin - A Title @end", "A Title", when, "", simple, ErrorMissingDate},
{"bad-date", "@begin not-a-real date - A Title @end", "A Title", when, "", simple, ErrorParsing},
{"one-field", "@begin " + whens + " - A Title\n@age 41 @end", "A Title", when, "", []Meta{{"age", 41}}, nil},
{
"two-fields",
"@begin " + whens + " - A Title\n@age 41\n@cool true @end",
"A Title",
when, "",
[]Meta{{"age", 41}, {"cool", true}},
nil,
},
{
"obj-field",
"@begin " + whens + " - A Title\n" + `@me {"name":"Dan","coder":true} @end`,
"A Title",
when, "",
[]Meta{{"me", json.RawMessage(`{"name":"Dan","coder":true}`)}},
nil,
},
{
"nested-field",
"@begin " + whens + " - A Title\n@me:name Dan\n@me:coder true @end",
"A Title",
when, "",
[]Meta{{"me:name", "Dan"}, {"me:coder", true}},
nil,
},
{
"nested-field-dot",
"@begin " + whens + " - A Title\n@me:name Dan Jones\n@me:name:nick Danny\n@me:coder true @end",
"A Title",
when, "",
[]Meta{{"me:name", "Dan Jones"}, {"me:name:nick", "Danny"}, {"me:coder", true}},
nil,
},
{
"json-field",
"@begin " + whens + " - Some Guy\n" + `@json {"name":"Dan","coder":true} @end`,
"Some Guy",
when, "",
[]Meta{{"name", "Dan"}, {"coder", true}},
nil,
},
}
for _, tt := range tests {
t.Run(tt.name, getEntryUnmarshalTestRunner(tt.in, tt.title, tt.date, tt.id, tt.fields, tt.err))
}
}
func getEntryUnmarshalTestRunner(in string, title string, date time.Time, id string, fields []Meta, err error) func(*testing.T) {
return func(t *testing.T) {
e := &Entry{}
er := e.UnmarshalText([]byte(in))
if err != nil {
be.Err(t, er, err)
return
}
be.Equal(t, e.Title, title)
be.True(t, e.Date.After(date.Add(-time.Second)) && e.Date.Before(date.Add(time.Second)))
if id != "" {
be.Equal(t, e.ID, id)
}
for _, f := range fields {
got := false
for _, m := range e.Fields {
var mVal any = m.Value
var fVal any = f.Value
if mJ, ok := m.Value.(json.RawMessage); ok {
mVal = string(mJ)
}
if fJ, ok := f.Value.(json.RawMessage); ok {
fVal = string(fJ)
}
if m.Key == f.Key && mVal == fVal {
got = true
break
}
}
be.True(t, got)
}
}
}
func TestScan(t *testing.T) {
in := "@begin date - Title\nlong\n@foo john\njones\n@bar 42@nobody @end"
read := strings.NewReader(in)
scan := bufio.NewScanner(read)
scan.Split(scanEntry)
be.True(t, scan.Scan())
be.Equal(t, scan.Text(), "@begin date - Title\nlong")
be.True(t, scan.Scan())
be.Equal(t, scan.Text(), "@foo john\njones")
be.True(t, scan.Scan())
be.Equal(t, scan.Text(), "@bar 42@nobody")
be.True(t, !scan.Scan())
}
func TestEntryJsonMarshal(t *testing.T) {
when := time.Now()
whens := when.Format(time.RFC3339)
simple := []Meta{}
tests := []struct {
name string
title string
date time.Time
fields []Meta
check func(*testing.T, []byte)
wantErr error
}{
{
"simple",
"A Title",
when,
simple,
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
be.Equal(t, m["title"].(string), "A Title")
be.Equal(t, m["date"].(string), whens)
_, hasID := m["id"].(string)
be.True(t, hasID)
},
nil,
},
{
"one-field",
"A Title 2",
when,
[]Meta{{"age", 41}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
be.Equal(t, m["title"].(string), "A Title 2")
be.Equal(t, m["date"].(string), whens)
be.Equal(t, m["age"].(float64), float64(41))
},
nil,
},
{
"skip-title-field",
"A Title",
when,
[]Meta{{"title", "Different title"}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
be.Equal(t, m["title"].(string), "A Title")
},
nil,
},
{
"skip-date-field",
"A Title",
when,
[]Meta{{"date", when.Add(time.Hour)}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
be.Equal(t, m["date"].(string), whens)
},
nil,
},
{
"skip-dupe-field",
"A Title",
when,
[]Meta{{"foo", "bar"}, {"foo", "baz"}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
be.Equal(t, m["foo"].(string), "bar")
},
nil,
},
{
"two-fields",
"A Title",
when,
[]Meta{{"foo", "bar"}, {"baz", 42}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
be.Equal(t, m["foo"].(string), "bar")
be.Equal(t, m["baz"].(float64), float64(42))
},
nil,
},
{
"empty-title",
"",
when,
simple,
nil,
ErrorMissingTitle,
},
{
"empty-date",
"A Title",
time.Time{},
simple,
nil,
ErrorMissingDate,
},
{
"obj-field",
"A Title",
when,
[]Meta{{"obj", json.RawMessage(`{"foo":"bar","title":"Sub-title"}`)}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
obj, ok := m["obj"].(map[string]any)
be.True(t, ok)
be.Equal(t, obj["foo"].(string), "bar")
be.Equal(t, obj["title"].(string), "Sub-title")
},
nil,
},
{
"date-field",
"A Title",
when,
[]Meta{{"when", when.Add(time.Hour)}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
be.Equal(t, m["when"].(string), when.Add(time.Hour).Format(time.RFC3339))
},
nil,
},
{
"json-field",
"A Title",
when,
[]Meta{{"json", json.RawMessage(`{"age": 41, "cool": true, "name": "Jim"}`)}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
be.Equal(t, m["age"].(float64), float64(41))
be.Equal(t, m["cool"].(bool), true)
be.Equal(t, m["name"].(string), "Jim")
},
nil,
},
{
"nested-field",
"A Title",
when,
[]Meta{{"obj:foo", "bar"}, {"obj:title", "Sub-title"}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
obj, ok := m["obj"].(map[string]any)
be.True(t, ok)
be.Equal(t, obj["foo"].(string), "bar")
be.Equal(t, obj["title"].(string), "Sub-title")
},
nil,
},
{
"double-nested-field",
"A Title",
when,
[]Meta{{"obj:foo", "bar"}, {"obj:me:name", "Dan"}, {"obj:me:age", 27}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
obj, ok := m["obj"].(map[string]any)
be.True(t, ok)
be.Equal(t, obj["foo"].(string), "bar")
me, ok := obj["me"].(map[string]any)
be.True(t, ok)
be.Equal(t, me["name"].(string), "Dan")
be.Equal(t, me["age"].(float64), float64(27))
},
nil,
},
{
"nested-plus-json",
"A Title",
when,
[]Meta{{"obj:foo", "bar"}, {"obj:me", json.RawMessage(`{"name":"Dan","age":27}`)}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
obj, ok := m["obj"].(map[string]any)
be.True(t, ok)
be.Equal(t, obj["foo"].(string), "bar")
me, ok := obj["me"].(map[string]any)
be.True(t, ok)
be.Equal(t, me["name"].(string), "Dan")
be.Equal(t, me["age"].(float64), float64(27))
},
nil,
},
{
"nested-part",
"A Title",
when,
[]Meta{{"obj:foo", "bar"}, {"obj:me", "Dan"}, {"obj:me:age", 27}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
obj, ok := m["obj"].(map[string]any)
be.True(t, ok)
be.Equal(t, obj["foo"].(string), "bar")
me, ok := obj["me"].(map[string]any)
be.True(t, ok)
be.Equal(t, me["."].(string), "Dan")
be.Equal(t, me["age"].(float64), float64(27))
},
nil,
},
{
"nested-part-order",
"A Title",
when,
[]Meta{{"obj:foo", "bar"}, {"obj:me:age", 27}, {"obj:me", "Dan"}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
obj, ok := m["obj"].(map[string]any)
be.True(t, ok)
be.Equal(t, obj["foo"].(string), "bar")
me, ok := obj["me"].(map[string]any)
be.True(t, ok)
be.Equal(t, me["."].(string), "Dan")
be.Equal(t, me["age"].(float64), float64(27))
},
nil,
},
{
"nested-part-order-two",
"A Title",
when,
[]Meta{{"obj:foo", "bar"}, {"obj:me:age", 27}, {"obj:me", "Dan"}, {"obj:me:cool", true}},
func(t *testing.T, o []byte) {
var m map[string]any
err := json.Unmarshal(o, &m)
be.Err(t, err, nil)
obj, ok := m["obj"].(map[string]any)
be.True(t, ok)
be.Equal(t, obj["foo"].(string), "bar")
me, ok := obj["me"].(map[string]any)
be.True(t, ok)
be.Equal(t, me["."].(string), "Dan")
be.Equal(t, me["age"].(float64), float64(27))
be.Equal(t, me["cool"].(bool), true)
},
nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := Entry{Title: tt.title, Date: tt.date, Fields: tt.fields}
o, er := json.Marshal(e)
if tt.wantErr == nil {
be.Err(t, er, nil)
tt.check(t, o)
} else {
be.Err(t, er, tt.wantErr)
}
})
}
}
func TestEntryJsonUnmarshal(t *testing.T) {
when := time.Now().Truncate(time.Second)
whens := when.Format(time.RFC3339)
simple := []Meta{}
tests := []struct {
name string
in string
title string
date time.Time
fields []Meta
err error
}{
{"simple", `{"title":"A Title","date":"` + whens + `"}`, "A Title", when, simple, nil},
{"missing-title", `{"date":"` + whens + `"}`, "", when, simple, ErrorMissingTitle},
{"missing-date", `{"title":"A Title"}`, "", when, simple, ErrorMissingDate},
{"empty-title", `{"title":"","date":"` + whens + `"}`, "", when, simple, ErrorMissingTitle},
{"empty-date", `{"title":"A Title","date":""}`, "", when, simple, ErrorMissingDate},
{"bad-date", `{"title":"A Title","date":"bad"}`, "", when, simple, ErrorParsing},
{"bad-json", `{"title":"A Title","date":"`, "", when, simple, ErrorParsing},
{
"single-field",
`{"title":"A Title","date":"` + whens + `","hello":"Hi"}`,
"A Title",
when,
[]Meta{{"hello", "Hi"}},
nil,
},
{
"many-fields",
`{"title":"A Title","date":"` + whens + `","hello":"Hi","bye":42,"b":true,"fl":42.13}`,
"A Title",
when,
[]Meta{{"hello", "Hi"}, {"bye", int64(42)}, {"b", true}, {"fl", float64(42.13)}},
nil,
},
{
"date-field",
`{"title":"A Title","date":"` + whens + `","posted":"` + when.Add(-time.Hour).In(time.UTC).Format(time.RFC3339) + `"}`,
"A Title",
when,
[]Meta{{"posted", when.Add(-time.Hour)}},
nil,
},
{
"json-field",
`{"title":"A Title","date":"` + whens + `","json":{"age": 41, "cool": true, "name": "Jim"}}`,
"A Title",
when,
[]Meta{{"age", int64(41)}, {"cool", true}, {"name", "Jim"}},
nil,
},
{
"json-field-embed",
`{"title":"A Title","date":"` + whens + `","json":"{\"age\": 41, \"cool\": true, \"name\": \"Jim\"}"}`,
"A Title",
when,
[]Meta{{"age", int64(41)}, {"cool", true}, {"name", "Jim"}},
nil,
},
}
for _, tt := range tests {
t.Run(tt.name, getEntryJsonUnmarshalTestRunner(tt.in, tt.title, tt.date, tt.fields, tt.err))
}
}
func getEntryJsonUnmarshalTestRunner(in, title string, date time.Time, fields []Meta, err error) func(t *testing.T) {
return func(t *testing.T) {
e := new(Entry)
er := e.UnmarshalJSON([]byte(in))
if err != nil {
be.Err(t, er, err)
return
}
be.Equal(t, er, nil)
be.Equal(t, e.Title, title)
be.True(t, e.Date.After(date.Add(-time.Second)) && e.Date.Before(date.Add(time.Second)))
be.Equal(t, len(e.Fields), len(fields))
for _, f := range fields {
got := false
fTime, isTime := f.Value.(time.Time)
for _, m := range e.Fields {
var mVal any = m.Value
var fVal any = f.Value
if mJ, ok := m.Value.(json.RawMessage); ok {
mVal = string(mJ)
}
if fJ, ok := f.Value.(json.RawMessage); ok {
fVal = string(fJ)
}
if m.Key == f.Key && mVal == fVal {
got = true
break
}
if isTime && m.Key == f.Key {
mTime, _ := mVal.(time.Time)
if mTime.After(fTime.Add(-2*time.Second)) && mTime.Before(fTime.Add(2*time.Second)) {
got = true
break
}
}
}
be.True(t, got)
}
}
}

View file

@ -1,14 +0,0 @@
package models
import (
"errors"
"fmt"
)
var ErrorMissingTitle = errors.New("Missing title")
var ErrorMissingDate = errors.New("Missing date")
var ErrorParsing = errors.New("Parsing Error")
func newParsingError(err error) error {
return fmt.Errorf("%w: %w", ErrorParsing, err)
}

View file

@ -1,69 +0,0 @@
package models
import (
"bufio"
"bytes"
"regexp"
"sync"
)
var reg = regexp.MustCompile("(?sm)^@begin .+?(^| )@end")
type Log struct {
Name string
Entries []Entry
}
func (l *Log) UnmarshalText(in []byte) error {
ch := l.getLogUnarshalChan(in)
for entry := range ch {
l.Entries = append(l.Entries, entry)
}
return nil
}
func scanLog(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
// done
return 0, nil, nil
}
m := reg.FindIndex(data)
if len(m) == 0 && atEOF {
// all trash
return len(data), nil, nil
} else if len(m) == 0 && !atEOF {
// get more
return 0, nil, nil
}
return m[1], data[m[0]:m[1]], nil
}
func (l *Log) getLogUnarshalChan(in []byte) chan Entry {
size := len(in) / 10 // rough estimation
ch := make(chan Entry, size)
var wg sync.WaitGroup
read := bytes.NewReader(in)
scan := bufio.NewScanner(read)
scan.Split(scanLog)
for scan.Scan() {
wg.Add(1)
go func(field []byte) {
defer wg.Done()
f := new(Entry)
err := f.UnmarshalText(field)
if err != nil {
return
}
ch <- *f
}(scan.Bytes())
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}

View file

@ -1,111 +0,0 @@
package models
import (
"encoding"
"testing"
"github.com/nalgeon/be"
)
var _ encoding.TextUnmarshaler = new(Log)
const first = "@begin January 01, 2020 at 01:02:03AM -0000 - This is simple @end\n"
const second = `@begin January 01, 2020 at 01:02:05AM -0000 - We have one thing here
@foo bar @end
`
const third = `@begin January 01, 2020 at 01:02:07AM -0000 - We have two things here
@num 42
@newline true
@end
`
const fourth = `@begin 2020-01-01T01:02:09Z - ISO-8601 date
@end
`
const skip = "@ignoreme true\n"
const fifth = `@begin 2020-01-01T01:02:11+00:00 - ISO-8601 other date
@with-timezone yes @end
`
const badEntry = "@begin bad date no title @end\n"
const all = first + second + third + fourth + skip + fifth
func TestLogUnmarshalBig(t *testing.T) {
l := &Log{Name: "test-log"}
err := l.UnmarshalText([]byte(all))
be.Err(t, err, nil)
be.Equal(t, len(l.Entries), 5)
var e Entry
var f bool
if e, f = findEntry(t, l, "This is simple", true); !f {
return
}
be.Equal(t, len(e.Fields), 0)
for _, e := range l.Entries {
findMeta(t, e, "ignoreme", true, false)
}
}
func TestLogUnmarshalIgnoreGarbage(t *testing.T) {
l := &Log{Name: "test-log"}
in := "ignore this\n" + second + "some crap also skip -> " + third + skip
err := l.UnmarshalText([]byte(in))
be.Err(t, err, nil)
be.Equal(t, len(l.Entries), 1)
en := l.Entries[0]
be.Equal(t, en.Title, "We have one thing here")
be.Equal(t, len(en.Fields), 1)
be.Equal(t, en.Fields[0].Key, "foo")
be.Equal(t, en.Fields[0].Value, "bar")
}
func TestLogUnmarshalEmpty(t *testing.T) {
l := &Log{Name: "test-log"}
err := l.UnmarshalText([]byte{})
be.Err(t, err, nil)
be.Equal(t, len(l.Entries), 0)
}
func TestLogUnmarshalBad(t *testing.T) {
l := &Log{Name: "test-log"}
err := l.UnmarshalText([]byte(badEntry))
be.Err(t, err, nil)
be.Equal(t, len(l.Entries), 0)
}
func findEntry(t *testing.T, log *Log, title string, shouldFind bool) (Entry, bool) {
var ret Entry
found := false
for _, e := range log.Entries {
if e.Title == title {
ret = e
found = true
}
}
if shouldFind {
be.True(t, found)
} else {
be.True(t, !found)
}
return ret, found
}
func findMeta(t *testing.T, entry Entry, key string, value any, shouldFind bool) (Meta, bool) {
var ret Meta
found := false
for _, m := range entry.Fields {
if m.Key == key && m.Value == value {
ret = m
found = true
}
}
if shouldFind {
be.True(t, found)
} else {
be.True(t, !found)
}
return ret, found
}

View file

@ -1,109 +0,0 @@
package models
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"regexp"
"codeberg.org/danjones000/my-log/tools"
)
type Meta struct {
Key string
Value any
}
func (m Meta) MarshalText() ([]byte, error) {
if regexp.MustCompile(`\s`).MatchString(m.Key) {
return []byte{}, fmt.Errorf("whitespace is not allowed in key: %s", m.Key)
}
buff := &bytes.Buffer{}
if jv, ok := m.Value.(map[string]any); ok {
err := marshalMap(m.Key, jv, buff)
return buff.Bytes(), err
}
if jj, ok := m.Value.(json.RawMessage); ok {
mp := map[string]any{}
err := json.Unmarshal(jj, &mp)
if err == nil {
err := marshalMap(m.Key, mp, buff)
return buff.Bytes(), err
}
}
if err := m.marshalToBuff(buff); err != nil {
return nil, err
}
return buff.Bytes(), nil
}
func marshalMap(pre string, mp map[string]any, buff *bytes.Buffer) error {
var idx uint
for k, v := range mp {
if idx > 0 {
buff.WriteRune('\n')
}
idx++
newKey := pre + ":" + k
if k == "." || k == "" {
newKey = pre
}
if subM, ok := v.(map[string]any); ok {
if err := marshalMap(newKey, subM, buff); err != nil {
return err
}
} else {
mSub := Meta{newKey, v}
if err := mSub.marshalToBuff(buff); err != nil {
return err
}
}
}
return nil
}
func (m Meta) marshalToBuff(buff *bytes.Buffer) error {
buff.WriteRune('@')
buff.WriteString(m.Key)
buff.WriteRune(' ')
n, err := tools.WriteValue(buff, m.Value)
if err != nil {
return err
}
if n == 0 {
return ErrorParsing
}
return nil
}
func (m *Meta) UnmarshalText(in []byte) error {
if len(in) == 0 {
return newParsingError(errors.New("Unable to Unmarshal empty string"))
}
re := regexp.MustCompile("(?s)^@([^ ]+) (.*)( @end)?$")
match := re.FindSubmatch(in)
if len(match) == 0 {
return newParsingError(fmt.Errorf("Failed to match %s", in))
}
m.Key = string(match[1])
return m.processMeta(match[2])
}
func (m *Meta) processMeta(in []byte) error {
if len(in) == 0 {
return newParsingError(errors.New("No value found"))
}
v := tools.ParseBytes(in)
if v == "" {
return newParsingError(errors.New("No value found"))
}
m.Value = v
return nil
}

View file

@ -1,218 +0,0 @@
package models
import (
"encoding"
"encoding/json"
"errors"
"testing"
"time"
"codeberg.org/danjones000/my-log/internal/testutil/bep"
"github.com/nalgeon/be"
)
// Type assertions
var _ encoding.TextMarshaler = Meta{}
var _ encoding.TextUnmarshaler = new(Meta)
var _ json.Marshaler = Metas{}
var _ json.Unmarshaler = new(Metas)
var skipMarshalTest = errors.New("skip marshal")
func TestMeta(t *testing.T) {
when := time.Now()
tests := []struct {
name string
key string
value any
out string
err error
newVal any
}{
{"int", "num", 42, "@num 42", nil, 42},
{"int64", "num", int64(42), "@num 42", nil, int(42)},
{"float", "num", 42.13, "@num 42.13", nil, 42.13},
{"string", "word", "hello", "@word hello", nil, "hello"},
{"json number", "num", json.Number("42.13"), "@num 42.13", nil, 42.13},
{"true", "b", true, "@b true", nil, true},
{"false", "b", false, "@b false", nil, false},
{"nil", "n", nil, "", ErrorParsing, ErrorParsing},
{"time", "when", when, "@when " + when.Format(time.RFC3339), nil, when},
{"rune", "char", '@', "@char @", nil, "@"},
{"bytes", "byteme", []byte("yo"), "@byteme yo", nil, "yo"},
{"byte", "byteme", byte(67), "@byteme C", nil, "C"},
{"json-arr", "arr", json.RawMessage(`["foo",42,"bar", null,"quux", true]`), `@arr ["foo",42,"bar", null,"quux", true]`, nil, json.RawMessage(`["foo",42,"bar", null,"quux", true]`)},
{"chan", "nope", make(chan bool), "", errors.New("Unsupported type chan bool"), ""},
{"whitespace-key", "no space", "hi", "", errors.New("whitespace is not allowed in key: no space"), ""},
{"empty-mar", "nope", skipMarshalTest, "", nil, ErrorParsing},
{"no-key-mar", "nope", skipMarshalTest, "nope", nil, ErrorParsing},
{"no-value-mar", "nope", skipMarshalTest, "@nope ", nil, ErrorParsing},
{"space-value-mar", "nope", skipMarshalTest, "@nope ", nil, ErrorParsing},
{"space-nl-value-mar", "nope", skipMarshalTest, "@nope \n ", nil, ErrorParsing},
{"null-value-mar", "nope", skipMarshalTest, "@nope null", nil, nil},
{"tilda-value-mar", "nope", skipMarshalTest, "@nope ~", nil, nil},
{"none-value-mar", "nope", skipMarshalTest, "@nope none", nil, nil},
{"nil-value-mar", "nope", skipMarshalTest, "@nope nil", nil, nil},
{"yes-value-mar", "nope", skipMarshalTest, "@nope yes", nil, true},
{"on-value-mar", "nope", skipMarshalTest, "@nope on", nil, true},
{"no-value-mar", "nope", skipMarshalTest, "@nope no", nil, false},
{"off-value-mar", "nope", skipMarshalTest, "@nope off", nil, false},
}
for _, tt := range tests {
t.Run(tt.name, getMetaTestRunner(tt.key, tt.value, tt.out, tt.err, tt.newVal))
}
}
func getMetaTestRunner(key string, value any, out string, err error, newVal any) func(*testing.T) {
return func(t *testing.T) {
st := Meta{key, value}
n := &Meta{}
var e error
if valE, ok := value.(error); !ok || !errors.Is(valE, skipMarshalTest) {
var o []byte
o, e = st.MarshalText()
be.Equal(t, string(o), out)
be.Equal(t, e, err)
if e != nil {
return
}
e = n.UnmarshalText(o)
} else {
e = n.UnmarshalText([]byte(out))
}
if newE, ok := newVal.(error); ok {
be.Err(t, e, newE)
} else {
be.Equal(t, n.Key, key)
if ti, ok := newVal.(time.Time); ok {
valT, ok := n.Value.(time.Time)
be.True(t, ok)
be.True(t, valT.After(ti.Add(-time.Second)) && valT.Before(ti.Add(time.Second)))
} else {
be.Equal(t, n.Value, newVal)
}
}
}
}
func TestMetasJson(t *testing.T) {
ms := Metas{{"me", 41}, {"you", false}}
exp := `{"me":41,"you":false}`
o, err := json.Marshal(ms)
be.Err(t, err, nil)
bep.JSON(t, o, []byte(exp))
}
func TestMetasJsonUnmarshal(t *testing.T) {
ms := Metas{}
in := `{"me":"cool","you":false}`
err := json.Unmarshal([]byte(in), &ms)
be.Err(t, err, nil)
be.Equal(t, len(ms), 2)
be.Equal(t, ms, Metas{
{"me", "cool"},
{"you", false},
})
}
func TestMetasJsonError(t *testing.T) {
ms := Metas{}
in := "not json"
err := (&ms).UnmarshalJSON([]byte(in))
be.Err(t, err)
be.Equal(t, len(ms), 0)
}
func TestMetasAppend(t *testing.T) {
ms := Metas{}
ms = ms.Append("foo", 42)
be.Equal(t, len(ms), 1)
be.Equal(t, ms[0], Meta{"foo", 42})
}
func TestMetasAppendTo(t *testing.T) {
ms := &Metas{}
ms.AppendTo("foo", 42)
be.Equal(t, len(*ms), 1)
be.Equal(t, (*ms)[0], Meta{"foo", 42})
}
func TestMetasSet(t *testing.T) {
tests := []struct {
name string
initial Metas
key string
value any
expected Metas
}{
{
name: "Set new key",
initial: Metas{},
key: "foo",
value: 42,
expected: Metas{{"foo", 42}},
},
{
name: "Update existing key",
initial: Metas{{"foo", 1}},
key: "foo",
value: 42,
expected: Metas{{"foo", 42}},
},
{
name: "Update existing key with different type",
initial: Metas{{"foo", "hello"}},
key: "foo",
value: 42,
expected: Metas{{"foo", 42}},
},
{
name: "Set multiple new keys",
initial: Metas{},
key: "bar",
value: true,
expected: Metas{{"bar", true}},
},
{
name: "Update one of multiple existing keys",
initial: Metas{{"foo", 1}, {"bar", "hello"}},
key: "foo",
value: 42,
expected: Metas{{"foo", 42}, {"bar", "hello"}},
},
{
name: "Set new key when others exist",
initial: Metas{{"foo", 1}, {"bar", "hello"}},
key: "baz",
value: false,
expected: Metas{{"foo", 1}, {"bar", "hello"}, {"baz", false}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := tt.initial.Set(tt.key, tt.value)
be.Equal(t, result, tt.expected)
})
}
}
func TestMetasGet(t *testing.T) {
ms := Metas{{"foo", 42}, {"bar", "hello"}}
val, found := ms.Get("foo")
be.True(t, found)
be.Equal(t, val, 42)
val, found = ms.Get("bar")
be.True(t, found)
be.Equal(t, val, "hello")
val, found = ms.Get("baz")
be.True(t, !found)
be.Equal(t, val, nil)
}

View file

@ -1,138 +0,0 @@
package models
import (
"encoding/json"
"strings"
"time"
)
// A slice of Meta
type Metas []Meta
// Returns a single map containing all the Meta. Is useful when encoding to JSON
func (ms Metas) Map() map[string]any {
out := map[string]any{}
for _, f := range ms {
if _, found := out[f.Key]; found || f.Key == "title" || f.Key == "date" {
continue
}
if f.Key == "json" {
ob := map[string]any{}
if j, ok := f.Value.(json.RawMessage); ok {
json.Unmarshal(j, &ob)
}
// If we couldn't get valid data from there, this will just be empty
for k, v := range ob {
if k != "title" && k != "date" {
out[k] = v
}
}
} else {
out[f.Key] = f.Value
if vt, ok := f.Value.(time.Time); ok {
out[f.Key] = vt.Format(time.RFC3339)
}
}
}
// Next we have to go through them again to find nested fields
parseNestedFields(out)
return out
}
func parseNestedFields(f map[string]any) {
todelete := make([]string, 0, len(f))
for k, v := range f {
if strings.Contains(k, ":") {
idx := strings.Index(k, ":")
top := k[:idx]
bottom := k[(idx + 1):]
nest, ok := f[top].(map[string]any)
if !ok {
curr := f[top]
if curr == nil {
nest = map[string]any{}
} else {
nest = map[string]any{".": curr}
}
}
curr, ok := nest[bottom].(map[string]any)
if ok {
curr["."] = v
} else {
nest[bottom] = v
}
parseNestedFields(nest)
f[top] = nest
todelete = append(todelete, k)
}
}
for _, k := range todelete {
delete(f, k)
}
}
// Implements json.Marshaler
func (ms Metas) MarshalJSON() ([]byte, error) {
return json.Marshal(ms.Map())
}
// Implements json.Unmarshaler
func (ms *Metas) UnmarshalJSON(in []byte) error {
old := (*ms).Map()
out := map[string]any{}
err := json.Unmarshal(in, &out)
if err != nil {
return err
}
ret := *ms
for k, v := range out {
if _, found := old[k]; k != "title" && k != "date" && !found {
ret = append(ret, Meta{k, v})
}
}
*ms = ret
return nil
}
// Returns a new Metas with a new Meta appended
func (ms Metas) Append(k string, v any) Metas {
return append(ms, Meta{k, v})
}
// Appends a new Meta to this Metas
func (ms *Metas) AppendTo(k string, v any) {
n := (*ms).Append(k, v)
*ms = n
}
// Returns the value of the Meta with the given key, and a bool indicating if it was found
func (ms Metas) Get(key string) (any, bool) {
_, m, ok := ms.findVal(key)
return m.Value, ok
}
// Set sets the key to the given value.
// If key is already in the ms, Set updates the value of the found Meta.
// If key is not in ms, then we append a new Meta and return the modified Metas.
func (ms Metas) Set(key string, value any) Metas {
idx, m, found := ms.findVal(key)
if !found {
return ms.Append(key, value)
}
m.Value = value
ms[idx] = m
return ms
}
func (ms Metas) findVal(key string) (idx int, m Meta, found bool) {
for idx, m = range ms {
if m.Key == key {
return idx, m, true
}
}
return 0, Meta{}, false
}

View file

@ -1,44 +0,0 @@
package tools
import (
"encoding/json"
"regexp"
"strconv"
"strings"
)
func ParseBytes(in []byte) any {
return ParseString(string(in))
}
var yesno = regexp.MustCompile("^(y|Y|yes|Yes|YES|n|N|no|No|NO|true|True|TRUE|false|False|FALSE|on|On|ON|off|Off|OFF)$")
var yes = regexp.MustCompile("^(y|Y|yes|Yes|YES|true|True|TRUE|on|On|ON)$")
var null = regexp.MustCompile("^(~|null|Null|NULL|none|None|NONE|nil|Nil|NIL)$")
func ParseString(in string) any {
s := strings.TrimSpace(in)
if s == "" {
return s
}
if strings.HasPrefix(s, "!") {
return s
}
var j json.RawMessage
if null.MatchString(s) {
return nil
} else if yesno.MatchString(s) {
return yes.MatchString(s)
} else if i, err := strconv.Atoi(s); err == nil {
return i
} else if f, err := strconv.ParseFloat(s, 64); err == nil {
return f
} else if t, err := ParseDate(s); err == nil {
return t
} else if err := json.Unmarshal([]byte(s), &j); err == nil {
return j
}
return s
}

View file

@ -1,70 +0,0 @@
package tools
import (
"strconv"
"time"
dp "github.com/markusmobius/go-dateparser"
"github.com/markusmobius/go-dateparser/date"
)
const DateFormat = "January 02, 2006 at 03:04:05PM -0700"
// These are somewhat arbitrary, but reasonably useful min and max times
var (
MinTime = time.Unix(-2208988800, 0) // Jan 1, 1900
MaxTime = MinTime.Add(1<<63 - 1)
)
func ParseDate(in string) (t time.Time, err error) {
if in == "min" {
return MinTime, nil
}
if in == "max" {
return MaxTime, nil
}
var er error
for _, format := range []string{time.RFC3339, DateFormat} {
if t, er = time.ParseInLocation(format, in, nil); er == nil {
return
}
}
var ts int64
if ts, er = strconv.ParseInt(in, 10, 0); er == nil {
t = time.Unix(ts, 0)
return
}
conf := dp.Configuration{
CurrentTime: time.Now().Local(),
ReturnTimeAsPeriod: true,
Languages: []string{"en"},
}
d, err := dp.Parse(&conf, in)
t = d.Time
if err != nil {
return
}
y, mon, day, h, loc := t.Year(), t.Month(), t.Day(), t.Hour(), t.Location()
switch d.Period {
case date.Second:
t = t.Truncate(time.Second)
case date.Minute:
t = t.Truncate(time.Minute)
case date.Hour:
t = time.Date(y, mon, day, h, 0, 0, 0, loc)
case date.Day:
t = time.Date(y, mon, day, 0, 0, 0, 0, loc)
case date.Month:
t = time.Date(y, mon, 1, 0, 0, 0, 0, loc)
case date.Year:
t = time.Date(y, 1, 1, 0, 0, 0, 0, loc)
}
return
}

View file

@ -1,66 +0,0 @@
package tools
import (
"fmt"
"testing"
"time"
"github.com/nalgeon/be"
)
const day = time.Hour * 24
func TestParseDate(t *testing.T) {
now := time.Now().Local()
y, mon, d, h, loc := now.Year(), now.Month(), now.Day(), now.Hour(), now.Location()
sec := now.Truncate(time.Second)
today := time.Date(y, mon, d, 0, 0, 0, 0, loc)
tomorrow := time.Date(y, mon, d+1, 0, 0, 0, 0, loc)
yesterday := time.Date(y, mon, d-1, 0, 0, 0, 0, loc)
twoMin := now.Add(2 * time.Minute).Truncate(time.Minute)
twoHour := time.Date(y, mon, d, h+2, 0, 0, 0, loc)
firstMonth := time.Date(y, mon, 1, 0, 0, 0, 0, loc)
firstYear := time.Date(y, 1, 1, 0, 0, 0, 0, loc)
exact := "2075-02-12T12:13:54.536-02:00"
exactd, _ := time.ParseInLocation(time.RFC3339, exact, nil)
var ts int64 = 1708876012
tsd := time.Unix(ts, 0)
ent := "February 25, 2024 at 04:00:13AM +0230"
entd, _ := time.Parse(DateFormat, ent)
tests := []struct {
name string
exp time.Time
err string
}{
{"now", sec, ""},
{"today", today, ""},
{"tomorrow", tomorrow, ""},
{"yesterday", yesterday, ""},
{"in two minutes", twoMin, ""},
{"in two hours", twoHour, ""},
{"this month", firstMonth, ""},
{"this year", firstYear, ""},
{"min", MinTime, ""},
{"max", MaxTime, ""},
{exact, exactd, ""},
{fmt.Sprint(ts), tsd, ""},
{ent, entd, ""},
{"not a date", now, fmt.Sprintf(`failed to parse "%s": unknown format`, "not a date")},
}
for _, tt := range tests {
t.Run(tt.name, getDateTest(tt.name, tt.exp, tt.err))
}
}
func getDateTest(in string, exp time.Time, err string) func(t *testing.T) {
return func(t *testing.T) {
out, er := ParseDate(in)
if err != "" {
be.Err(t, er, err)
} else {
be.Err(t, er, nil)
be.Equal(t, out, exp)
}
}
}

View file

@ -1,71 +0,0 @@
package tools
import (
"encoding/json"
"testing"
"time"
"github.com/nalgeon/be"
)
func TestParse(t *testing.T) {
when := time.Now()
now := when.Local().Truncate(time.Second)
tests := []struct {
name string
in string
out any
}{
{"int", "42", 42},
{"float", "42.13", 42.13},
{"string", "hello", "hello"},
{"true", "true", true},
{"false", "false", false},
{"nil", "nil", nil},
{"time", when.Format(time.RFC3339), when},
{"now", "now", now},
{"DateFormat", now.Format(DateFormat), now},
{"json-obj", `{"foo":"bar","baz":"quux"}`, json.RawMessage(`{"foo":"bar","baz":"quux"}`)},
{"json-arr", `["foo",42,"bar", null,"quux", true]`, json.RawMessage(`["foo",42,"bar", null,"quux", true]`)},
{"empty", "", ""},
{"space-value", " ", ""},
{"space-nl-value", " \n ", ""},
{"null-value", "null", nil},
{"tilda-value", "~", nil},
{"none-value", "none", nil},
{"nil-value", "nil", nil},
{"yes-value", "yes", true},
{"on-value", "on", true},
{"no-value", "no", false},
{"off-value", "off", false},
{"skip-parsing-num", "!42", "!42"},
{"skip-parsing-bool", "!false", "!false"},
{"skip-parsing-time", "!" + when.Format(time.RFC3339), "!" + when.Format(time.RFC3339)},
{"skip-parsing-duration", "!15 mins", "!15 mins"},
}
for _, tt := range tests {
t.Run(tt.name, getParseTestRunner(tt.in, tt.out))
}
}
func getParseTestRunner(in string, exp any) func(*testing.T) {
return func(t *testing.T) {
out := ParseString(in)
if expT, ok := exp.(time.Time); ok {
ti, gotTime := out.(time.Time)
be.True(t, gotTime)
be.True(t, expT.After(ti.Add(-2*time.Second)) && expT.Before(ti.Add(2*time.Second)))
} else {
be.Equal(t, out, exp)
}
out = ParseBytes([]byte(in))
if expT, ok := exp.(time.Time); ok {
ti, gotTime := out.(time.Time)
be.True(t, gotTime)
be.True(t, expT.After(ti.Add(-2*time.Second)) && expT.Before(ti.Add(2*time.Second)))
} else {
be.Equal(t, out, exp)
}
}
}

View file

@ -1,63 +0,0 @@
package tools
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
)
func WriteValue(buff *bytes.Buffer, val any) (n int, err error) {
switch v := val.(type) {
default:
err = fmt.Errorf("Unsupported type %T", v)
case nil:
return
case []any:
var o []byte
o, err = json.Marshal(v)
if err == nil {
return buff.Write(o)
}
case map[string]any:
var o []byte
o, err = json.Marshal(v)
if err == nil {
return buff.Write(o)
}
case string:
if after, ok := strings.CutPrefix(v, "!"); ok {
return buff.WriteString(after)
}
return buff.WriteString(v)
case int:
return buff.WriteString(strconv.Itoa(v))
case int64:
return buff.WriteString(strconv.FormatInt(v, 10))
case float64:
return buff.WriteString(strconv.FormatFloat(v, 'f', -1, 64))
case json.Number:
return buff.WriteString(v.String())
case json.RawMessage:
return buff.Write(v)
case []byte:
if v[0] == '!' {
return buff.Write(v[1:])
}
return buff.Write(v)
case byte:
err = buff.WriteByte(v)
if err == nil {
n = 1
}
case rune:
return buff.WriteString(string(v))
case bool:
return buff.WriteString(strconv.FormatBool(v))
case time.Time:
return buff.WriteString(v.Format(time.RFC3339))
}
return
}

View file

@ -1,59 +0,0 @@
package tools
import (
"bytes"
"encoding/json"
"errors"
"testing"
"time"
"github.com/nalgeon/be"
)
func TestWriteBuffer(t *testing.T) {
when := time.Now()
tests := []struct {
name string
value any
out string
err error
}{
{"nil", nil, "", nil},
{"string", "hi", "hi", nil},
{"bytes", []byte{104, 105}, "hi", nil},
{"byte", byte(104), "h", nil},
{"rune", 'h', "h", nil},
{"int", 42, "42", nil},
{"int64", int64(42), "42", nil},
{"float", 42.13, "42.13", nil},
{"bool", false, "false", nil},
{"json.Number", json.Number("42.13"), "42.13", nil},
{"json.RawMessage", json.RawMessage("{}"), "{}", nil},
{"time", when, when.Format(time.RFC3339), nil},
{"slice", []any{1, 2, "foo"}, `[1,2,"foo"]`, nil},
{"map", map[string]any{"baz": 42, "foo": "bar"}, `{"baz":42,"foo":"bar"}`, nil},
{"struct", struct{}{}, "", errors.New("Unsupported type struct {}")},
{"skip-bang-num", "!42", "42", nil},
{"skip-bang-bool", "!false", "false", nil},
{"skip-bang-time", "!" + when.Format(time.RFC3339), when.Format(time.RFC3339), nil},
{"skip-bang-duration", "!15 mins", "15 mins", nil},
{"skip-bang-bytes-num", []byte("!42"), "42", nil},
{"skip-bang-bytes-bool", []byte("!false"), "false", nil},
{"skip-bang-bytes-time", []byte("!" + when.Format(time.RFC3339)), when.Format(time.RFC3339), nil},
{"skip-bang-bytes-duration", []byte("!15 mins"), "15 mins", nil},
}
for _, tt := range tests {
t.Run(tt.name, getWriteTestRunner(tt.value, tt.out, tt.err))
}
}
func getWriteTestRunner(value any, out string, err error) func(*testing.T) {
return func(t *testing.T) {
buff := &bytes.Buffer{}
n, er := WriteValue(buff, value)
be.Equal(t, n, len(out))
be.Equal(t, er, err)
be.Equal(t, buff.String(), out)
}
}

113
ytdlp/drop.go Normal file
View file

@ -0,0 +1,113 @@
package ytdlp
import (
"context"
"fmt"
"strings"
"time"
"codeberg.org/danjones000/my-log/files"
"codeberg.org/danjones000/my-log/models"
ytd "github.com/lrstanley/go-ytdlp"
)
// Drop adds the URL specified by the url to the watched log.
func Drop(ctx context.Context, url string) (models.Log, error) {
var ent models.Entry
var log models.Log
if ctx.Err() != nil {
return log, context.Cause(ctx)
}
info, err := Fetch(ctx, url)
if err != nil {
return log, err
}
now := time.Now()
ent.Date = now
metas := &ent.Fields
*metas = metas.Set("id", getID(now, info))
source := FirstNonZero(info.ExtractorKey, info.WebpageURLDomain, new("Web Video"))
*metas = metas.Set("source", source)
ent.Title = FirstNonZero(info.Title, info.AltTitle, new(fmt.Sprintf("%s %s", source, info.ID)))
setNote(metas, info)
setArtist(metas, info)
setTags(metas, info)
setUrl(metas, info, url)
// TODO Add show info
log = models.Log{Name: "watched", Entries: []models.Entry{ent}}
if err := files.Append(log); err != nil {
return log, err
}
return log, nil
}
func getID(now time.Time, info *ytd.ExtractedInfo) string {
id := new(strings.Builder)
id.WriteString("tag:")
id.WriteString(FirstNonZero(info.WebpageURLDomain, new("goodevilgenius.org")))
id.WriteByte(',')
id.WriteString(now.Format("2006"))
id.WriteRune(':')
id.WriteString(info.ID)
id.WriteRune('/')
fmt.Fprintf(id, "%d", now.Unix())
return id.String()
}
func setNote(metas *models.Metas, info *ytd.ExtractedInfo) {
desc := FirstNonZero(info.Description)
if desc != "" {
desc = strings.SplitN(desc, "\n", 2)[0]
*metas = metas.Set("note", desc)
}
}
func setArtist(metas *models.Metas, info *ytd.ExtractedInfo) {
art := FirstNonZero(info.Artist, info.AlbumArtist, info.Uploader)
if art != "" {
*metas = metas.Set("artist", art)
}
}
func setTags(metas *models.Metas, info *ytd.ExtractedInfo) {
tags := make([]any, 0, len(info.Tags)+len(info.Categories))
for _, t := range info.Tags {
tags = append(tags, t)
}
for _, c := range info.Categories {
tags = append(tags, c)
}
if len(tags) > 0 {
*metas = metas.Set("tags", tags)
}
}
func setDuration(metas *models.Metas, info *ytd.ExtractedInfo) {
dur := FirstNonZero(info.Duration)
if dur > 0 {
*metas = metas.Set("duration", dur)
}
}
func setUrl(metas *models.Metas, info *ytd.ExtractedInfo, origUrl string) {
url := FirstNonZero(info.WebpageURL, info.PageURL, info.URL, &origUrl)
*metas = metas.Set("url", url)
}
func FirstNonZero[T comparable](vals ...*T) T {
var z T
for _, v := range vals {
if v != nil && *v != z {
return *v
}
}
return z
}

28
ytdlp/fetch.go Normal file
View file

@ -0,0 +1,28 @@
package ytdlp
import (
"context"
"fmt"
ytd "github.com/lrstanley/go-ytdlp"
)
// Fetch fetches info from a video on YouTube or other sites supported by yt-dlp
func Fetch(ctx context.Context, url string) (*ytd.ExtractedInfo, error) {
dl := ytd.New().DumpJSON().RemoteComponents("ejs:github")
// TODO Add cookies if available
res, err := dl.Run(ctx, url)
if err != nil {
return nil, err
}
infos, err := res.GetExtractedInfo()
if err != nil {
return nil, err
}
if len(infos) != 1 {
return nil, fmt.Errorf("%d infos", len(infos))
}
return infos[0], nil
}