├── .dockerignore ├── pkg ├── archive │ ├── testdata │ │ └── unzip.zip │ ├── unzip_test.go │ └── unzip.go ├── localdb │ ├── testdata │ │ └── test.metadata.json │ ├── jsondb_test.go │ └── jsondb.go ├── errors │ ├── message.go │ └── message_test.go ├── consumer │ ├── queue.go │ └── notify.go └── paperless │ ├── client.go │ ├── document.go │ ├── download.go │ ├── upload.go │ └── query.go ├── test ├── consume.env ├── local.mk └── docker-compose.yml ├── .gitignore ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── bug_report.md │ └── feature_request.md ├── workflows │ ├── test.yml │ ├── build.yml │ ├── lint.yml │ └── release.yml ├── PULL_REQUEST_TEMPLATE.md └── changelog-configuration.json ├── Dockerfile ├── package ├── systemd.service └── systemd.env ├── Makefile.vars.mk ├── renovate.json ├── logger.go ├── go.mod ├── main.go ├── Makefile ├── init_command.go ├── consume_command.go ├── .goreleaser.yml ├── README.md ├── upload_command.go ├── flags.go ├── bulk_download_command.go ├── go.sum └── LICENSE /.dockerignore: -------------------------------------------------------------------------------- 1 | .* 2 | * 3 | !paperless-cli 4 | -------------------------------------------------------------------------------- /pkg/archive/testdata/unzip.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ccremer/paperless-cli/HEAD/pkg/archive/testdata/unzip.zip -------------------------------------------------------------------------------- /pkg/localdb/testdata/test.metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "documents": [ 3 | { 4 | "id": 2 5 | }, 6 | { 7 | "id": 15 8 | } 9 | ] 10 | } 11 | -------------------------------------------------------------------------------- /test/consume.env: -------------------------------------------------------------------------------- 1 | export PAPERLESS_USERNAME=admin 2 | export PAPERLESS_TOKEN=admin 3 | export PAPERLESS_URL=http://localhost:8008 4 | export CONSUME_DIR=./.work/consume 5 | export CONSUME_DELAY=3s 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Goreleaser 2 | /dist/ 3 | /.github/release-notes.md 4 | 5 | # Build 6 | /paperless-cli 7 | *.out 8 | 9 | # work 10 | /.work/ 11 | 12 | /documents.zip 13 | /documents 14 | /config.yaml 15 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: [] 3 | # - name: ❓ Question 4 | # url: https://github.com/ccremer/paperless-cli/discussions 5 | # about: Ask or discuss with me, I'm happy to help 🙋 6 | -------------------------------------------------------------------------------- /pkg/errors/message.go: -------------------------------------------------------------------------------- 1 | package errors 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func Wrap(err error, format string, args ...any) error { 8 | if err == nil { 9 | return nil 10 | } 11 | return fmt.Errorf("%s: %w", fmt.Sprintf(format, args...), err) 12 | } 13 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM docker.io/library/alpine:3.19 as runtime 2 | 3 | ENTRYPOINT ["paperless-cli"] 4 | 5 | RUN \ 6 | apk add --update --no-cache \ 7 | bash \ 8 | curl \ 9 | ca-certificates \ 10 | tzdata 11 | 12 | COPY paperless-cli /usr/bin/ 13 | USER 65536:0 14 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | pull_request: 5 | paths-ignore: 6 | - charts/** 7 | - docs/** 8 | 9 | jobs: 10 | go: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | 15 | - uses: actions/setup-go@v5 16 | with: 17 | go-version-file: 'go.mod' 18 | 19 | - name: Run tests 20 | run: make test-unit 21 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | pull_request: 5 | paths-ignore: 6 | - charts/** 7 | - docs/** 8 | 9 | jobs: 10 | go: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | 15 | - uses: actions/setup-go@v5 16 | with: 17 | go-version-file: 'go.mod' 18 | 19 | - name: Run build 20 | run: make build-docker 21 | -------------------------------------------------------------------------------- /package/systemd.service: -------------------------------------------------------------------------------- 1 | # This is a systemd unit file 2 | [Unit] 3 | Description=consumption service for paperless-ngx remote API 4 | Documentation=https://github.com/ccremer/paperless-cli 5 | After=network-online.target 6 | Wants=network-online.target 7 | 8 | [Service] 9 | EnvironmentFile=-/etc/default/paperless-cli 10 | User=65534 11 | Group=0 12 | ExecStart=/usr/bin/paperless-cli consume 13 | Restart=on-failure 14 | 15 | [Install] 16 | WantedBy=multi-user.target 17 | -------------------------------------------------------------------------------- /test/local.mk: -------------------------------------------------------------------------------- 1 | compose_file = test/docker-compose.yml 2 | compose_project = paperless-cli 3 | 4 | clean_targets += local-uninstall 5 | 6 | .PHONY: local-install 7 | local-install: | $(consume_dir) ## Install paperless-ngx in docker-compose 8 | docker-compose -f $(compose_file) -p $(compose_project) up -d 9 | 10 | .PHONY: local-uninstall 11 | local-uninstall: ## Uninstall paperless-ngx in docker-compose 12 | docker-compose -f $(compose_file) -p $(compose_project) rm --force --stop -v 13 | 14 | $(consume_dir): 15 | mkdir -p $@ 16 | -------------------------------------------------------------------------------- /Makefile.vars.mk: -------------------------------------------------------------------------------- 1 | ## These are some common variables for Make 2 | 3 | PROJECT_ROOT_DIR = . 4 | PROJECT_NAME ?= paperless-cli 5 | PROJECT_OWNER ?= ccremer 6 | 7 | WORK_DIR = $(PWD)/.work 8 | 9 | ## BUILD:go 10 | BIN_FILENAME ?= $(PROJECT_NAME) 11 | go_bin ?= $(WORK_DIR)/bin 12 | $(go_bin): 13 | @mkdir -p $@ 14 | 15 | ## BUILD:docker 16 | DOCKER_CMD ?= docker 17 | 18 | IMG_TAG ?= latest 19 | CONTAINER_REGISTRY ?= ghcr.io 20 | # Image URL to use all building/pushing image targets 21 | CONTAINER_IMG ?= $(CONTAINER_REGISTRY)/$(PROJECT_OWNER)/$(PROJECT_NAME):$(IMG_TAG) 22 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint 2 | 3 | on: 4 | pull_request: {} 5 | 6 | jobs: 7 | go: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v4 11 | 12 | - uses: actions/setup-go@v5 13 | with: 14 | go-version-file: 'go.mod' 15 | 16 | - name: Run linters 17 | run: make lint-go git-diff 18 | 19 | - name: golangci-lint 20 | uses: golangci/golangci-lint-action@v6 21 | with: 22 | version: latest 23 | skip-pkg-cache: true 24 | args: --timeout 5m --out-${NO_FUTURE}format colored-line-number 25 | -------------------------------------------------------------------------------- /pkg/consumer/queue.go: -------------------------------------------------------------------------------- 1 | package consumer 2 | 3 | import ( 4 | "context" 5 | "sync" 6 | ) 7 | 8 | type Queue[T any] struct { 9 | m sync.Map 10 | ch chan T 11 | } 12 | 13 | func NewQueue[T any]() *Queue[T] { 14 | return &Queue[T]{ 15 | ch: make(chan T), 16 | } 17 | } 18 | 19 | func (q *Queue[T]) Put(v T) { 20 | _, loaded := q.m.LoadOrStore(v, nil) 21 | if !loaded { 22 | q.ch <- v 23 | } 24 | } 25 | 26 | func (q *Queue[T]) Subscribe(ctx context.Context, fn func(v T)) { 27 | go func() { 28 | for { 29 | select { 30 | case <-ctx.Done(): 31 | break 32 | case v := <-q.ch: 33 | q.m.Delete(v) 34 | fn(v) 35 | } 36 | } 37 | }() 38 | } 39 | -------------------------------------------------------------------------------- /package/systemd.env: -------------------------------------------------------------------------------- 1 | ### General 2 | 3 | ## (Required) Target URL of the paperless-ngx instance. 4 | PAPERLESS_URL= 5 | 6 | ## Username of the Paperless API user. Can be left empty if only using a Token. 7 | PAPERLESS_USERNAME= 8 | ## (Required) Token or Password of the Paperless API user. 9 | PAPERLESS_TOKEN= 10 | 11 | ### Consuming files and upload them 12 | 13 | ## (Required) The directory path in which files are consumed (uploaded + deleted). 14 | CONSUME_DIR= 15 | 16 | ## The delay after detecting the last file write operation before uploading it. 17 | # CONSUME_DELAY=1s 18 | 19 | ### Misc 20 | 21 | ## Logging level. Increased numbers are more verbose. 22 | # LOG_LEVEL=0 23 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🐛 Bug report 3 | about: Create a report to help improve 🎉 4 | title: '[Bug] ' 5 | labels: 'bug' 6 | 7 | --- 8 | 9 | ## Describe the bug 10 | 11 | A clear and concise description of what the bug is. 12 | 13 | ## Additional context 14 | 15 | Add any other context about the problem here. 16 | 17 | ## Logs 18 | 19 | If applicable, add logs to help explain your problem. 20 | ```console 21 | 22 | ``` 23 | 24 | ## Expected behavior 25 | 26 | A clear and concise description of what you expected to happen. 27 | 28 | ## To Reproduce 29 | 30 | Steps to reproduce the behavior: 31 | 1. ... 32 | 33 | ## Environment (please complete the following information): 34 | 35 | - App Version: e.g. v1.0 36 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Summary 2 | 3 | * Short summary of what's included in the PR 4 | * Give special note to breaking changes: List the exact changes or provide links to documentation. 5 | 6 | ## Checklist 7 | 8 | ### For Code changes 9 | 10 | - [ ] Categorize the PR by setting a good title and adding one of the labels: 11 | `kind:bug`, `kind:enhancement`, `kind:documentation`, `kind:change`, `kind:breaking`, `kind:dependency` 12 | as they show up in the changelog 13 | - [ ] Link this PR to related issues 14 | 15 | 22 | -------------------------------------------------------------------------------- /pkg/archive/unzip_test.go: -------------------------------------------------------------------------------- 1 | package archive 2 | 3 | import ( 4 | "context" 5 | "os" 6 | "path/filepath" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | func TestUnzip(t *testing.T) { 14 | testFilePath := "testdata/unzip.zip" 15 | testDir := "testdata/run" 16 | 17 | // cleanup previous test files in case of failure 18 | require.NoError(t, os.RemoveAll(testDir)) 19 | 20 | err := Unzip(context.TODO(), testFilePath, testDir) 21 | assert.NoError(t, err, "unzip failed with error") 22 | 23 | assert.FileExists(t, filepath.Join(testDir, "toplevel.file")) 24 | assert.FileExists(t, filepath.Join(testDir, "Dir In Archive", "Sub Dir.file")) 25 | 26 | // cleanup 27 | require.NoError(t, os.RemoveAll(testDir)) 28 | } 29 | -------------------------------------------------------------------------------- /pkg/paperless/client.go: -------------------------------------------------------------------------------- 1 | package paperless 2 | 3 | import ( 4 | "net/http" 5 | ) 6 | 7 | type Client struct { 8 | URL string 9 | HttpClient *http.Client 10 | 11 | username string 12 | token string 13 | } 14 | 15 | // NewClient creates a new PaperlessClient using the given URL and credentials. 16 | // If using token auth, `username` parameter can be left empty. 17 | func NewClient(url, username, passwordOrToken string) *Client { 18 | return &Client{ 19 | URL: url, 20 | HttpClient: http.DefaultClient, 21 | username: username, 22 | token: passwordOrToken, 23 | } 24 | } 25 | 26 | func (clt *Client) setAuth(req *http.Request) { 27 | if clt.username == "" { 28 | req.Header.Set("Authorization", "Token "+clt.token) 29 | } else { 30 | req.SetBasicAuth(clt.username, clt.token) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /pkg/paperless/document.go: -------------------------------------------------------------------------------- 1 | package paperless 2 | 3 | type Document struct { 4 | // ID of the document, read-only. 5 | ID int `json:"id"` 6 | // OriginalFileName of the original document, read-only. 7 | OriginalFileName string `json:"original_file_name,omitempty"` 8 | // ArchivedFileName of the archived document, read-only. 9 | // May be empty if no archived document is available. 10 | ArchivedFileName string `json:"archived_file_name,omitempty"` 11 | } 12 | 13 | func MapToDocumentIDs(docs []Document) []int { 14 | ids := make([]int, len(docs)) 15 | for i := 0; i < len(docs); i++ { 16 | ids[i] = docs[i].ID 17 | } 18 | return ids 19 | } 20 | 21 | func MapToDocumentMap(docs []Document) map[int]Document { 22 | docM := make(map[int]Document, len(docs)) 23 | for _, doc := range docs { 24 | docM[doc.ID] = doc 25 | } 26 | return docM 27 | } 28 | -------------------------------------------------------------------------------- /.github/changelog-configuration.json: -------------------------------------------------------------------------------- 1 | { 2 | "pr_template": "- ${{TITLE}} by @${{AUTHOR}} (#${{NUMBER}})", 3 | "categories": [ 4 | { 5 | "title": "## 🚀 Features", 6 | "labels": [ 7 | "kind:enhancement" 8 | ] 9 | }, 10 | { 11 | "title": "## 🛠️ Minor Changes", 12 | "labels": [ 13 | "kind:change" 14 | ] 15 | }, 16 | { 17 | "title": "## 🔎 Breaking Changes", 18 | "labels": [ 19 | "kind:breaking" 20 | ] 21 | }, 22 | { 23 | "title": "## 🐛 Fixes", 24 | "labels": [ 25 | "kind:bug" 26 | ] 27 | }, 28 | { 29 | "title": "## 📄 Documentation", 30 | "labels": [ 31 | "kind:documentation" 32 | ] 33 | }, 34 | { 35 | "title": "## 🔗 Dependency Updates", 36 | "labels": [ 37 | "kind:dependency" 38 | ] 39 | } 40 | ], 41 | "template": "${{CATEGORIZED_COUNT}} changes since ${{FROM_TAG}}\n\n${{CHANGELOG}}" 42 | } 43 | -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:base", 5 | ":gitSignOff", 6 | ":disableDependencyDashboard" 7 | ], 8 | "labels": [ 9 | "kind:dependency" 10 | ], 11 | "postUpdateOptions": [ 12 | "gomodTidy" 13 | ], 14 | "packageRules": [ 15 | { 16 | "matchPackagePatterns": [ 17 | "golang.org/x/*" 18 | ], 19 | "groupName": "utils", 20 | "schedule": [ 21 | "on the first day of the month" 22 | ], 23 | "automerge": true 24 | }, 25 | { 26 | "matchPackagePatterns": [ 27 | "github.com/urfave/cli/v2" 28 | ], 29 | "groupName": "urfave/cli/v2", 30 | "schedule": [ 31 | "on the first day of the month" 32 | ] 33 | }, 34 | { 35 | "matchPaths": [ 36 | "docs/**" 37 | ], 38 | "groupName": "npm", 39 | "schedule": [ 40 | "on the first day of the month" 41 | ], 42 | "automerge": true 43 | } 44 | ] 45 | } 46 | -------------------------------------------------------------------------------- /pkg/errors/message_test.go: -------------------------------------------------------------------------------- 1 | package errors 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestWrap(t *testing.T) { 11 | tests := map[string]struct { 12 | err error 13 | msg string 14 | args []any 15 | expectedError string 16 | }{ 17 | "NilError_ReturnNil": { 18 | err: nil, 19 | }, 20 | "WithMessageNoArgs": { 21 | err: errors.New("failure"), 22 | msg: "this operation failed", 23 | args: nil, 24 | expectedError: "this operation failed: failure", 25 | }, 26 | "WithMessageAndArgs": { 27 | err: errors.New("failure"), 28 | msg: "this operation failed with %s", 29 | args: []any{"argument"}, 30 | expectedError: "this operation failed with argument: failure", 31 | }, 32 | } 33 | for name, tt := range tests { 34 | t.Run(name, func(t *testing.T) { 35 | result := Wrap(tt.err, tt.msg, tt.args...) 36 | if tt.expectedError != "" { 37 | assert.EqualError(t, result, tt.expectedError) 38 | } else { 39 | assert.NoError(t, result) 40 | } 41 | }) 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /logger.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "runtime" 6 | 7 | "github.com/ccremer/plogr" 8 | "github.com/go-logr/logr" 9 | "github.com/urfave/cli/v2" 10 | ) 11 | 12 | var logger logr.Logger 13 | 14 | func init() { 15 | // Remove `-v` short option from --version flag 16 | cli.VersionFlag.(*cli.BoolFlag).Aliases = nil 17 | } 18 | 19 | // LogMetadata prints various metadata to the root logger. 20 | // It prints version, architecture and current user ID and returns nil. 21 | func LogMetadata(c *cli.Context) error { 22 | log := logr.FromContextOrDiscard(c.Context) 23 | log.WithValues( 24 | "version", version, 25 | "date", date, 26 | "commit", commit, 27 | "go_os", runtime.GOOS, 28 | "go_arch", runtime.GOARCH, 29 | "go_version", runtime.Version(), 30 | "uid", os.Getuid(), 31 | "gid", os.Getgid(), 32 | ).Info("Starting up " + appName) 33 | return nil 34 | } 35 | 36 | func setupLogging(c *cli.Context) error { 37 | sink := newSink(c.Int(newLogLevelFlag().Name)) 38 | logger = logr.New(sink) 39 | c.Context = logr.NewContext(c.Context, logger) 40 | return nil 41 | } 42 | 43 | func newSink(level int) *plogr.PtermSink { 44 | sink := plogr.NewPtermSink() 45 | sink.ErrorPrinter.ShowLineNumber = true 46 | for i := 1; i <= level; i++ { 47 | sink.SetLevelEnabled(i, true) 48 | } 49 | return &sink 50 | } 51 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/ccremer/paperless-cli 2 | 3 | go 1.21 4 | 5 | toolchain go1.21.4 6 | 7 | require ( 8 | github.com/ccremer/plogr v0.7.0 9 | github.com/fsnotify/fsnotify v1.7.0 10 | github.com/go-logr/logr v1.4.1 11 | github.com/pterm/pterm v0.12.79 12 | github.com/stretchr/testify v1.9.0 13 | github.com/urfave/cli/v2 v2.27.1 14 | gopkg.in/yaml.v3 v3.0.1 15 | ) 16 | 17 | require ( 18 | atomicgo.dev/cursor v0.2.0 // indirect 19 | atomicgo.dev/keyboard v0.2.9 // indirect 20 | atomicgo.dev/schedule v0.1.0 // indirect 21 | github.com/BurntSushi/toml v1.3.2 // indirect 22 | github.com/containerd/console v1.0.3 // indirect 23 | github.com/cpuguy83/go-md2man/v2 v2.0.3 // indirect 24 | github.com/davecgh/go-spew v1.1.1 // indirect 25 | github.com/gookit/color v1.5.4 // indirect 26 | github.com/lithammer/fuzzysearch v1.1.8 // indirect 27 | github.com/mattn/go-runewidth v0.0.15 // indirect 28 | github.com/pmezard/go-difflib v1.0.0 // indirect 29 | github.com/rivo/uniseg v0.4.4 // indirect 30 | github.com/russross/blackfriday/v2 v2.1.0 // indirect 31 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect 32 | github.com/xrash/smetrics v0.0.0-20231213231151-1d8dd44e695e // indirect 33 | golang.org/x/sys v0.16.0 // indirect 34 | golang.org/x/term v0.16.0 // indirect 35 | golang.org/x/text v0.14.0 // indirect 36 | ) 37 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🚀 Feature request 3 | about: Suggest an idea for this project 💡 4 | title: '[Feature] ' 5 | labels: 'enhancement' 6 | 7 | --- 8 | 13 | 14 | ## Summary 15 | 16 | **As** role name 17 | **I want** a feature or functionality 18 | **So that** business value(s) 19 | 20 | ## Context 21 | 22 | Add more information here. You are completely free regarding form and length 23 | 24 | ## Out of Scope 25 | 26 | * List aspects that are explicitly not part of this feature 27 | 28 | ## Further links 29 | 30 | * URLs of relevant Git repositories, PRs, Issues, etc. 31 | 32 | ## Acceptance criteria 33 | 34 | 40 | 41 | ```gherkin 42 | Given a precondition 43 | When an action happens 44 | Then a result is expected 45 | ``` 46 | 47 | ## Implementation Ideas 48 | 49 | * If applicable, shortly list possible implementation ideas 50 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*" 7 | 8 | env: 9 | CONTAINER_REGISTRY: ghcr.io 10 | 11 | jobs: 12 | dist: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | with: 17 | fetch-depth: 0 18 | 19 | - uses: actions/setup-go@v5 20 | with: 21 | go-version-file: 'go.mod' 22 | 23 | - name: Set up QEMU 24 | uses: docker/setup-qemu-action@v3 25 | 26 | - name: Set up Docker Buildx 27 | uses: docker/setup-buildx-action@v3 28 | 29 | - name: Login to ${{ env.CONTAINER_REGISTRY }} 30 | uses: docker/login-action@v3 31 | with: 32 | registry: ${{ env.CONTAINER_REGISTRY }} 33 | username: ${{ github.repository_owner }} 34 | password: ${{ secrets.GITHUB_TOKEN }} 35 | 36 | - name: Generate artifacts 37 | run: make release-prepare 38 | 39 | - name: Build changelog from PRs with labels 40 | id: build_changelog 41 | uses: mikepenz/release-changelog-builder-action@v4 42 | with: 43 | configuration: ".github/changelog-configuration.json" 44 | outputFile: .github/release-notes.md 45 | ignorePreReleases: "${{ !contains(github.ref, '-rc') }}" 46 | env: 47 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 48 | 49 | - name: Publish releases 50 | uses: goreleaser/goreleaser-action@v6 51 | with: 52 | args: release --release-notes .github/release-notes.md 53 | env: 54 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 55 | IMAGE_NAME: ${{ github.repository }} 56 | -------------------------------------------------------------------------------- /test/docker-compose.yml: -------------------------------------------------------------------------------- 1 | # docker-compose file for running paperless from the Docker Hub. 2 | # This file contains everything paperless needs to run. 3 | # Paperless supports amd64, arm and arm64 hardware. 4 | # 5 | # All compose files of paperless configure paperless in the following way: 6 | # 7 | # - Paperless is (re)started on system boot, if it was running before shutdown. 8 | # - Docker volumes for storing data are managed by Docker. 9 | # - Folders for importing and exporting files are created in the same directory 10 | # as this file and mounted to the correct folders inside the container. 11 | # - Paperless listens on port 8000. 12 | # 13 | # SQLite is used as the database. The SQLite file is stored in the data volume. 14 | # 15 | # To install and update paperless with this file, do the following: 16 | # 17 | # - Copy this file as 'docker-compose.yml' and the files 'docker-compose.env' 18 | # and '.env' into a folder. 19 | # - Run 'docker-compose pull'. 20 | # - Run 'docker-compose run --rm webserver createsuperuser' to create a user. 21 | # - Run 'docker-compose up -d'. 22 | # 23 | # For more extensive installation and update instructions, refer to the 24 | # documentation. 25 | 26 | version: "3.4" 27 | services: 28 | broker: 29 | image: docker.io/library/redis:7 30 | restart: unless-stopped 31 | volumes: 32 | - redisdata:/data 33 | 34 | webserver: 35 | image: ghcr.io/paperless-ngx/paperless-ngx:latest 36 | restart: unless-stopped 37 | depends_on: 38 | - broker 39 | ports: 40 | - "8008:8000" 41 | environment: 42 | PAPERLESS_REDIS: redis://broker:6379 43 | PAPERLESS_ADMIN_USER: admin 44 | PAPERLESS_ADMIN_PASSWORD: admin 45 | PAPERLESS_FILENAME_FORMAT: "{created_year}/{correspondent}/{title}" 46 | 47 | volumes: 48 | redisdata: 49 | -------------------------------------------------------------------------------- /pkg/consumer/notify.go: -------------------------------------------------------------------------------- 1 | package consumer 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "math" 7 | "sync" 8 | "time" 9 | 10 | "github.com/fsnotify/fsnotify" 11 | "github.com/go-logr/logr" 12 | ) 13 | 14 | func StartWatchingDir(ctx context.Context, dir string, resetDelay time.Duration, callback func(filePath string)) error { 15 | log := logr.FromContextOrDiscard(ctx) 16 | watcher, err := fsnotify.NewWatcher() 17 | if err != nil { 18 | return err 19 | } 20 | 21 | go func() { 22 | waitFor := resetDelay 23 | 24 | // Keep track of the timers, as [path]timer. 25 | timers := sync.Map{} 26 | 27 | for { 28 | select { 29 | case <-ctx.Done(): 30 | log.V(1).Info("Stopping watcher") 31 | break 32 | case err, ok := <-watcher.Errors: 33 | if !ok { 34 | return 35 | } 36 | log.Error(err, "") 37 | case e, ok := <-watcher.Events: 38 | if !ok { 39 | return 40 | } 41 | 42 | // We just want to watch for file creation, so ignore everything outside Create and Write. 43 | if !e.Has(fsnotify.Create) && !e.Has(fsnotify.Write) { 44 | continue 45 | } 46 | log.V(2).Info("New Event", "name", e.Name, "op", e.Op) 47 | 48 | // Get timer. 49 | t, exists := timers.Load(e.Name) 50 | 51 | if !exists { 52 | t = time.AfterFunc(math.MaxInt64, func() { 53 | log.V(2).Info("Deleted timer", "name", e.Name) 54 | timers.Delete(e.Name) 55 | callback(e.Name) 56 | }) 57 | t.(*time.Timer).Stop() 58 | timers.Store(e.Name, t) 59 | } 60 | // Reset the timer for this path, so it will start the delay again. 61 | log.V(3).Info("Resetting timer", "delay", waitFor) 62 | t.(*time.Timer).Reset(waitFor) 63 | } 64 | } 65 | }() 66 | err = watcher.Add(dir) 67 | if err != nil { 68 | return fmt.Errorf("cannot start watcher: %w", err) 69 | } 70 | log.V(1).Info("Started watcher", "dir", dir) 71 | return nil 72 | } 73 | -------------------------------------------------------------------------------- /pkg/localdb/jsondb_test.go: -------------------------------------------------------------------------------- 1 | package localdb 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/ccremer/paperless-cli/pkg/paperless" 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestOpen(t *testing.T) { 11 | tests := map[string]struct { 12 | testFileName string 13 | expectedDocuments map[int]paperless.Document 14 | }{ 15 | "ExistingJSONFile": { 16 | testFileName: "test.metadata.json", 17 | expectedDocuments: map[int]paperless.Document{ 18 | 2: {ID: 2}, 19 | 15: {ID: 15}, 20 | }, 21 | }, 22 | "NonExistingJSONFile": { 23 | testFileName: "nonexisting.metadata.json", 24 | expectedDocuments: map[int]paperless.Document{}, 25 | }, 26 | } 27 | for name, tt := range tests { 28 | t.Run(name, func(t *testing.T) { 29 | old := fileName 30 | fileName = tt.testFileName 31 | defer func() { 32 | fileName = old 33 | }() 34 | 35 | result, err := Open("testdata") 36 | assert.NoError(t, err) 37 | assert.Equal(t, tt.expectedDocuments, result.documents) 38 | assert.Equal(t, "testdata/"+tt.testFileName, result.filePath) 39 | }) 40 | } 41 | } 42 | 43 | func TestDatabase_GetAll(t *testing.T) { 44 | tests := map[string]struct { 45 | givenDocuments map[int]paperless.Document 46 | expectedDocuments []paperless.Document 47 | }{ 48 | "NoDocuments": { 49 | givenDocuments: map[int]paperless.Document{}, 50 | expectedDocuments: []paperless.Document{}, 51 | }, 52 | "SeveralDocuments": { 53 | givenDocuments: map[int]paperless.Document{ 54 | 15: {ID: 15}, 55 | 1: {ID: 1}, 56 | }, 57 | expectedDocuments: []paperless.Document{ 58 | {ID: 1}, 59 | {ID: 15}, 60 | }, 61 | }, 62 | } 63 | for name, tt := range tests { 64 | t.Run(name, func(t *testing.T) { 65 | db := &Database{documents: tt.givenDocuments} 66 | result := db.GetAll() 67 | assert.Equal(t, tt.expectedDocuments, result) 68 | }) 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "time" 7 | 8 | "github.com/ccremer/plogr" 9 | "github.com/urfave/cli/v2" 10 | ) 11 | 12 | var ( 13 | // These will be populated by Goreleaser 14 | version = "unknown" 15 | commit = "-dirty-" 16 | date = time.Now().Format("2006-01-02") 17 | 18 | appName = "paperless-cli" 19 | appLongName = "CLI tool to interact with paperless-ngx remote API " 20 | 21 | // envPrefix is the global prefix to use for the keys in environment variables 22 | envPrefix = "PAPERLESS_" 23 | ) 24 | 25 | func main() { 26 | app := NewApp() 27 | err := app.Run(os.Args) 28 | if err != nil { 29 | plogr.DefaultErrorPrinter.Println(err.Error()) 30 | os.Exit(1) 31 | } 32 | } 33 | 34 | func NewApp() *cli.App { 35 | app := &cli.App{ 36 | Name: appName, 37 | Usage: appLongName, 38 | Version: fmt.Sprintf("%s, revision=%s, date=%s", version, commit, date), 39 | 40 | Before: before(loadConfigFileFn, setupLogging), 41 | Flags: []cli.Flag{ 42 | newLogLevelFlag(), 43 | newConfigFileFlag(), 44 | }, 45 | Commands: []*cli.Command{ 46 | &newUploadCommand().Command, 47 | &newBulkDownloadCommand().Command, 48 | &newConsumeCommand().Command, 49 | &newInitCommand().Command, 50 | }, 51 | } 52 | return app 53 | } 54 | 55 | // env combines envPrefix with given suffix delimited by underscore. 56 | func env(suffix string) string { 57 | return envPrefix + suffix 58 | } 59 | 60 | // envVars combines envPrefix with each given suffix delimited by underscore. 61 | func envVars(suffixes ...string) []string { 62 | arr := make([]string, len(suffixes)) 63 | for i := range suffixes { 64 | arr[i] = env(suffixes[i]) 65 | } 66 | return arr 67 | } 68 | 69 | func before(actions ...cli.BeforeFunc) cli.BeforeFunc { 70 | return func(ctx *cli.Context) error { 71 | for _, fn := range actions { 72 | if err := fn(ctx); err != nil { 73 | return err 74 | } 75 | } 76 | return nil 77 | } 78 | } 79 | 80 | func actions(actions ...cli.ActionFunc) cli.ActionFunc { 81 | return func(ctx *cli.Context) error { 82 | for _, action := range actions { 83 | if err := action(ctx); err != nil { 84 | return err 85 | } 86 | } 87 | return nil 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /pkg/archive/unzip.go: -------------------------------------------------------------------------------- 1 | package archive 2 | 3 | import ( 4 | "archive/zip" 5 | "context" 6 | "fmt" 7 | "io" 8 | "os" 9 | "path/filepath" 10 | "strings" 11 | 12 | "github.com/go-logr/logr" 13 | ) 14 | 15 | // Unzip reads and copies every file in the archive to the destination dir. 16 | func Unzip(ctx context.Context, source, dest string) error { 17 | log := logr.FromContextOrDiscard(ctx) 18 | log.V(1).Info("Unzipping file", "source", source, "dest", dest) 19 | archive, openErr := zip.OpenReader(source) 20 | if openErr != nil { 21 | return fmt.Errorf("cannot open source file: %w", openErr) 22 | } 23 | defer archive.Close() 24 | 25 | for _, f := range archive.File { 26 | destFilePath := filepath.Join(dest, f.Name) 27 | 28 | if !strings.HasPrefix(destFilePath, filepath.Clean(dest)+string(os.PathSeparator)) { 29 | return fmt.Errorf("invalid file path: %s", destFilePath) 30 | } 31 | if f.FileInfo().IsDir() { 32 | log.V(2).Info("Creating directory", "dir", f.FileInfo().Name()) 33 | if mkdirErr := os.MkdirAll(destFilePath, os.ModePerm); mkdirErr != nil { 34 | return fmt.Errorf("cannot create directory: %w", mkdirErr) 35 | } 36 | continue 37 | } 38 | log.V(2).Info("Extracting file", "source", f.Name, "dest", destFilePath) 39 | 40 | err := unzipFile(f, destFilePath) 41 | if err != nil { 42 | return err 43 | } 44 | } 45 | return nil 46 | } 47 | 48 | func unzipFile(f *zip.File, destFilePath string) error { 49 | // ensure directory exists where file should be written. 50 | if mkdirErr := os.MkdirAll(filepath.Dir(destFilePath), os.ModePerm); mkdirErr != nil { 51 | return fmt.Errorf("cannot create directory: %w", mkdirErr) 52 | } 53 | 54 | dstFile, dstFileErr := os.OpenFile(destFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) 55 | if dstFileErr != nil { 56 | return fmt.Errorf("cannot open destination file: %w", dstFileErr) 57 | } 58 | defer dstFile.Close() 59 | 60 | fileInArchive, srcFileErr := f.Open() 61 | if srcFileErr != nil { 62 | return fmt.Errorf("cannot open source file: %w", srcFileErr) 63 | } 64 | fileInArchive.Close() 65 | 66 | if _, copyErr := io.Copy(dstFile, fileInArchive); copyErr != nil { 67 | return fmt.Errorf("cannot copy %q to %q: %w", f.Name, dstFile.Name(), copyErr) 68 | } 69 | return nil 70 | } 71 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Set Shell to bash, otherwise some targets fail with dash/zsh etc. 2 | SHELL := /bin/bash 3 | .SHELLFLAGS := -eu -o pipefail -c 4 | 5 | # Disable built-in rules 6 | MAKEFLAGS += --no-builtin-rules 7 | MAKEFLAGS += --no-builtin-variables 8 | .SUFFIXES: 9 | .SECONDARY: 10 | .DEFAULT_GOAL := help 11 | 12 | # extensible array of targets. Modules can add target to this variable for the all-in-one target. 13 | clean_targets := build-clean release-clean 14 | test_targets := test-unit 15 | 16 | # General variables 17 | include Makefile.vars.mk 18 | 19 | # Following includes do not print warnings or error if files aren't found 20 | # Optional Documentation module. 21 | -include docs/docs.mk 22 | # Optional local env module. 23 | -include test/local.mk 24 | 25 | .PHONY: help 26 | help: ## Show this help 27 | @grep -E -h '\s##\s' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}' 28 | 29 | .PHONY: build 30 | build: build-docker ## All-in-one build 31 | 32 | .PHONY: build-bin 33 | build-bin: export CGO_ENABLED = 0 34 | build-bin: fmt vet ## Build binary 35 | @go build $(go_build_args) -o $(BIN_FILENAME) . 36 | 37 | .PHONY: build-docker 38 | build-docker: build-bin ## Build docker image 39 | $(DOCKER_CMD) build -t $(CONTAINER_IMG) . 40 | 41 | build-clean: ## Deletes binary and docker image 42 | rm -rf $(BIN_FILENAME) dist/ 43 | $(DOCKER_CMD) rmi $(CONTAINER_IMG) || true 44 | 45 | .PHONY: test 46 | test: $(test_targets) ## All-in-one test 47 | 48 | .PHONY: test-unit 49 | test-unit: ## Run unit tests against code 50 | go test -race -covermode atomic ./... 51 | 52 | .PHONY: fmt 53 | fmt: ## Run 'go fmt' against code 54 | go fmt ./... 55 | 56 | .PHONY: vet 57 | vet: ## Run 'go vet' against code 58 | go vet ./... 59 | 60 | .PHONY: lint 61 | lint: lint-go git-diff ## All-in-one linting 62 | 63 | .PHONY: lint-go 64 | lint-go: fmt vet generate ## Run linting for Go code 65 | go run . init - 66 | 67 | .PHONY: git-diff 68 | git-diff: 69 | @echo 'Check for uncommitted changes ...' 70 | git diff --exit-code 71 | 72 | .PHONY: generate 73 | generate: generate-go ## All-in-one code generation 74 | 75 | .PHONY: generate-go 76 | generate-go: ## Generate Go artifacts 77 | @go generate ./... 78 | 79 | .PHONY: release-prepare 80 | release-prepare: ## Prepares artifacts for releases 81 | 82 | .PHONY: release-clean 83 | release-clean: 84 | 85 | .PHONY: clean 86 | clean: $(clean_targets) ## All-in-one target to cleanup local artifacts 87 | -------------------------------------------------------------------------------- /init_command.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/urfave/cli/v2" 8 | "github.com/urfave/cli/v2/altsrc" 9 | "gopkg.in/yaml.v3" 10 | ) 11 | 12 | type InitCommand struct { 13 | cli.Command 14 | } 15 | 16 | func newInitCommand() *InitCommand { 17 | c := &InitCommand{} 18 | c.Command = cli.Command{ 19 | Name: "init", 20 | Usage: "Initializes a config file", 21 | Description: `If CONFIG-FILE is "-" the YAML will be printed to stdout. 22 | If empty, it will be written to "config.yaml".`, 23 | Action: c.Action, 24 | ArgsUsage: "[CONFIG-FILE]", 25 | } 26 | return c 27 | } 28 | 29 | func (c *InitCommand) Action(ctx *cli.Context) error { 30 | configFilePath := "config.yaml" 31 | if ctx.NArg() >= 1 { 32 | configFilePath = ctx.Args().First() 33 | } 34 | 35 | flags := allAltSrcFlags(ctx) 36 | values := map[string]any{} 37 | for _, flag := range flags { 38 | values[flag.Names()[0]] = getValueFor(flag) 39 | } 40 | b, err := yaml.Marshal(values) 41 | if err != nil { 42 | return fmt.Errorf("cannot serialize flags to yaml: %w", err) 43 | } 44 | 45 | if configFilePath == "-" { 46 | fmt.Println(string(b)) 47 | return nil 48 | } 49 | if _, statErr := os.Stat(configFilePath); statErr != nil && os.IsNotExist(statErr) { 50 | return os.WriteFile(configFilePath, b, 0644) 51 | } 52 | return fmt.Errorf("target file %q exists already", configFilePath) 53 | } 54 | 55 | func getValueFor(flag cli.Flag) any { 56 | if f, ok := flag.(*altsrc.StringFlag); ok { 57 | return f.Value 58 | } 59 | if f, ok := flag.(*altsrc.BoolFlag); ok { 60 | return f.Value 61 | } 62 | if f, ok := flag.(*altsrc.DurationFlag); ok { 63 | return f.Value 64 | } 65 | if f, ok := flag.(*altsrc.IntFlag); ok { 66 | return f.Value 67 | } 68 | panic(fmt.Errorf("unknown flag type: %v", flag)) 69 | } 70 | 71 | func allAltSrcFlags(ctx *cli.Context) []cli.Flag { 72 | flagMap := map[string]cli.Flag{} 73 | for _, flag := range ctx.App.Flags { 74 | if f, isAltSrcFlag := flag.(altsrc.FlagInputSourceExtension); isAltSrcFlag { 75 | flagMap[flag.Names()[0]] = f 76 | } 77 | } 78 | for _, subcommand := range ctx.App.Commands { 79 | for _, flag := range subcommand.Flags { 80 | if f, isAltSrcFlag := flag.(altsrc.FlagInputSourceExtension); isAltSrcFlag { 81 | flagMap[flag.Names()[0]] = f 82 | } 83 | } 84 | } 85 | flags := make([]cli.Flag, 0) 86 | for _, flag := range flagMap { 87 | flags = append(flags, flag) 88 | } 89 | return flags 90 | } 91 | -------------------------------------------------------------------------------- /pkg/localdb/jsondb.go: -------------------------------------------------------------------------------- 1 | package localdb 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "os" 7 | "path/filepath" 8 | "sort" 9 | 10 | "github.com/ccremer/paperless-cli/pkg/errors" 11 | "github.com/ccremer/paperless-cli/pkg/paperless" 12 | ) 13 | 14 | type metadataContainer struct { 15 | Documents []paperless.Document `json:"documents,omitempty"` 16 | } 17 | 18 | var fileName = ".metadata.json" 19 | 20 | // Database is a simple wrapper around a JSON-based file. 21 | type Database struct { 22 | documents map[int]paperless.Document 23 | filePath string 24 | } 25 | 26 | // Open reads the database file from the given directory. 27 | // An error is returned if the file doesn't exist or cannot be read. 28 | // There can only be 1 database per directory. 29 | func Open(documentDir string) (*Database, error) { 30 | filePath := filepath.Join(documentDir, fileName) 31 | container := metadataContainer{} 32 | 33 | raw, err := os.ReadFile(filePath) 34 | if err != nil { 35 | if os.IsNotExist(err) { 36 | raw = []byte("{}") 37 | } else { 38 | return nil, fmt.Errorf("cannot open metadata file: %w", err) 39 | } 40 | } 41 | parseErr := json.Unmarshal(raw, &container) 42 | if parseErr != nil { 43 | return nil, fmt.Errorf("cannot parse metadata file %s: %w", filePath, err) 44 | } 45 | docs := paperless.MapToDocumentMap(container.Documents) 46 | return &Database{ 47 | filePath: filePath, 48 | documents: docs, 49 | }, nil 50 | } 51 | 52 | // FindByID returns the document by the given ID, or nil if not existing. 53 | func (d *Database) FindByID(id int) *paperless.Document { 54 | if doc, found := d.documents[id]; found { 55 | return &doc 56 | } 57 | return nil 58 | } 59 | 60 | // GetAll returns all documents sorted by ID. 61 | func (d *Database) GetAll() []paperless.Document { 62 | docs := make([]paperless.Document, len(d.documents)) 63 | i := 0 64 | for _, document := range d.documents { 65 | docs[i] = document 66 | i++ 67 | } 68 | sort.Slice(docs, func(i, j int) bool { 69 | return docs[i].ID < docs[j].ID 70 | }) 71 | return docs 72 | } 73 | 74 | // Put adds or updates a document. 75 | func (d *Database) Put(doc paperless.Document) { 76 | d.documents[doc.ID] = doc 77 | } 78 | 79 | // Remove deletes the given document 80 | func (d *Database) Remove(doc paperless.Document) { 81 | delete(d.documents, doc.ID) 82 | } 83 | 84 | // Close saves the database. 85 | func (d *Database) Close() error { 86 | container := metadataContainer{Documents: d.GetAll()} 87 | b, err := json.Marshal(container) 88 | if err != nil { 89 | return fmt.Errorf("cannot save database: %w", err) 90 | } 91 | return errors.Wrap(os.WriteFile(d.filePath, b, 0644), "cannot save database") 92 | } 93 | -------------------------------------------------------------------------------- /consume_command.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/fs" 6 | "os" 7 | "path/filepath" 8 | "time" 9 | 10 | "github.com/ccremer/paperless-cli/pkg/consumer" 11 | "github.com/ccremer/paperless-cli/pkg/paperless" 12 | "github.com/go-logr/logr" 13 | "github.com/urfave/cli/v2" 14 | ) 15 | 16 | type ConsumeCommand struct { 17 | cli.Command 18 | 19 | PaperlessURL string 20 | PaperlessToken string 21 | PaperlessUser string 22 | 23 | ConsumeDirName string 24 | ConsumeDelay time.Duration 25 | } 26 | 27 | func newConsumeCommand() *ConsumeCommand { 28 | c := &ConsumeCommand{} 29 | c.Command = cli.Command{ 30 | Name: "consume", 31 | Usage: "Consumes a local directory and uploads each file to Paperless instance. The files will be deleted once uploaded.", 32 | Before: loadConfigFileFn, 33 | Action: actions(LogMetadata, c.Action), 34 | 35 | Flags: []cli.Flag{ 36 | newURLFlag(&c.PaperlessURL), 37 | newUsernameFlag(&c.PaperlessUser), 38 | newTokenFlag(&c.PaperlessToken), 39 | newConsumeDirFlag(&c.ConsumeDirName), 40 | newConsumeDelayFlag(&c.ConsumeDelay), 41 | }, 42 | } 43 | return c 44 | } 45 | 46 | func (c *ConsumeCommand) Action(ctx *cli.Context) error { 47 | log := logr.FromContextOrDiscard(ctx.Context) 48 | log.Info("Start consuming directory", "dir", c.ConsumeDirName) 49 | 50 | clt := paperless.NewClient(c.PaperlessURL, c.PaperlessUser, c.PaperlessToken) 51 | q := consumer.NewQueue[string]() 52 | q.Subscribe(ctx.Context, func(fileName string) { 53 | log.V(1).Info("Uploading file...", "file", fileName) 54 | err := clt.Upload(ctx.Context, fileName, paperless.UploadParams{}) 55 | if err != nil { 56 | log.Error(err, "Could not upload file") 57 | return 58 | } 59 | if deleteErr := os.Remove(fileName); deleteErr != nil { 60 | log.Error(err, "Could not delete file, this might be re-uploaded later again", "file", fileName) 61 | } 62 | log.Info("File uploaded", "file", fileName) 63 | }) 64 | 65 | walkErr := filepath.WalkDir(c.ConsumeDirName, func(path string, entry fs.DirEntry, err error) error { 66 | if path == c.ConsumeDirName { 67 | return nil // same directory, not interesting 68 | } 69 | if entry.IsDir() { 70 | return fs.SkipDir 71 | } 72 | if err != nil { 73 | return fs.SkipDir 74 | } 75 | q.Put(path) 76 | return nil 77 | }) 78 | if walkErr != nil { 79 | return fmt.Errorf("cannot walk consumption dir: %w", walkErr) 80 | } 81 | 82 | watchErr := consumer.StartWatchingDir(ctx.Context, c.ConsumeDirName, c.ConsumeDelay, func(filePath string) { 83 | q.Put(filePath) 84 | }) 85 | if watchErr != nil { 86 | return fmt.Errorf("cannot watch consumption dir: %w", watchErr) 87 | } 88 | <-make(chan struct{}) 89 | return nil 90 | } 91 | -------------------------------------------------------------------------------- /pkg/paperless/download.go: -------------------------------------------------------------------------------- 1 | package paperless 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "encoding/json" 7 | "fmt" 8 | "io" 9 | "net/http" 10 | "os" 11 | 12 | "github.com/ccremer/paperless-cli/pkg/errors" 13 | "github.com/go-logr/logr" 14 | ) 15 | 16 | type BulkDownloadContent string 17 | 18 | type BulkDownloadParams struct { 19 | DocumentIDs []int 20 | FollowFormatting bool 21 | Content BulkDownloadContent 22 | } 23 | 24 | const ( 25 | BulkDownloadBoth BulkDownloadContent = "both" 26 | BulkDownloadArchives BulkDownloadContent = "archive" 27 | BulkDownloadOriginal BulkDownloadContent = "originals" 28 | ) 29 | 30 | // String implements fmt.Stringer. 31 | func (c BulkDownloadContent) String() string { 32 | return string(c) 33 | } 34 | 35 | // BulkDownload downloads the documents identified by BulkDownloadParams.DocumentIDs and saves to the given targetPath. 36 | // If targetPath is empty, it will use the suggested file name from Paperless in the current working dir. 37 | func (clt *Client) BulkDownload(ctx context.Context, targetFile *os.File, params BulkDownloadParams) error { 38 | req, err := clt.makeBulkDownloadRequest(ctx, params) 39 | if err != nil { 40 | return err 41 | } 42 | 43 | log := logr.FromContextOrDiscard(ctx) 44 | log.V(1).Info("Awaiting response") 45 | resp, err := clt.HttpClient.Do(req) 46 | if err != nil { 47 | return fmt.Errorf("request failed: %w", err) 48 | } 49 | defer resp.Body.Close() 50 | 51 | if resp.StatusCode != http.StatusOK { 52 | b, _ := io.ReadAll(resp.Body) 53 | return fmt.Errorf("request failed: %s: %s", resp.Status, string(b)) 54 | } 55 | 56 | log.V(1).Info("Writing download content to file", "file", targetFile.Name()) 57 | _, err = io.Copy(targetFile, resp.Body) 58 | return errors.Wrap(err, "cannot read response body") 59 | } 60 | 61 | func (clt *Client) makeBulkDownloadRequest(ctx context.Context, params BulkDownloadParams) (*http.Request, error) { 62 | log := logr.FromContextOrDiscard(ctx) 63 | 64 | js := map[string]any{ 65 | "content": params.Content, 66 | "follow_formatting": params.FollowFormatting, 67 | "documents": params.DocumentIDs, 68 | } 69 | marshal, err := json.Marshal(js) 70 | if err != nil { 71 | return nil, fmt.Errorf("cannot serialize to JSON: %w", err) 72 | } 73 | body := bytes.NewReader(marshal) 74 | 75 | path := clt.URL + "/api/documents/bulk_download/" 76 | log.V(1).Info("Preparing request", "path", path, "document_ids", params.DocumentIDs) 77 | req, err := http.NewRequestWithContext(ctx, "POST", path, body) 78 | if err != nil { 79 | return nil, fmt.Errorf("cannot prepare request: %w", err) 80 | } 81 | clt.setAuth(req) 82 | req.Header.Set("Content-Type", "application/json") 83 | return req, nil 84 | } 85 | -------------------------------------------------------------------------------- /.goreleaser.yml: -------------------------------------------------------------------------------- 1 | # Make sure to check the documentation at http://goreleaser.com 2 | builds: 3 | - env: 4 | - CGO_ENABLED=0 # this is needed otherwise the Docker image build is faulty 5 | goarch: 6 | - amd64 7 | - arm 8 | - arm64 9 | goos: 10 | - linux 11 | - windows 12 | goarm: 13 | - 7 14 | 15 | archives: 16 | - format: binary 17 | name_template: "{{ .Binary }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" 18 | 19 | checksum: 20 | name_template: checksums.txt 21 | 22 | snapshot: 23 | name_template: "{{ .Tag }}-snapshot" 24 | 25 | nfpms: 26 | - vendor: ccremer 27 | homepage: https://github.com/ccremer/paperless-cli 28 | maintainer: ccremer 29 | description: CLI tool to interact with paperless-ngx remote API 30 | license: GPLv3 31 | file_name_template: "{{ .Binary }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}" 32 | formats: 33 | - deb 34 | - rpm 35 | contents: 36 | - src: package/systemd.service 37 | dst: /lib/systemd/system/paperless-consume.service 38 | - src: package/systemd.env 39 | dst: /etc/default/paperless-cli 40 | type: config 41 | 42 | dockers: 43 | - goarch: amd64 44 | use: buildx 45 | build_flag_templates: 46 | - "--platform=linux/amd64" 47 | image_templates: 48 | - "{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:v{{ .Version }}-amd64" 49 | 50 | - goarch: arm64 51 | use: buildx 52 | build_flag_templates: 53 | - "--platform=linux/arm64/v8" 54 | image_templates: 55 | - "{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:v{{ .Version }}-arm64" 56 | 57 | - goarch: arm 58 | goarm: 7 59 | use: buildx 60 | build_flag_templates: 61 | - "--platform=linux/arm/v7" 62 | image_templates: 63 | - "{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:v{{ .Version }}-armv7" 64 | 65 | docker_manifests: 66 | ## ghcr.io 67 | # For prereleases, updating `latest` does not make sense. 68 | # Only the image for the exact version should be pushed. 69 | - name_template: "{{ if not .Prerelease }}{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:latest{{ end }}" 70 | image_templates: 71 | - "{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:v{{ .Version }}-amd64" 72 | - "{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:v{{ .Version }}-arm64" 73 | - "{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:v{{ .Version }}-armv7" 74 | 75 | - name_template: "{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:v{{ .Version }}" 76 | image_templates: 77 | - "{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:v{{ .Version }}-amd64" 78 | - "{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:v{{ .Version }}-arm64" 79 | - "{{ .Env.CONTAINER_REGISTRY }}/{{ .Env.IMAGE_NAME }}:v{{ .Version }}-armv7" 80 | 81 | release: 82 | prerelease: auto 83 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # paperless-cli 2 | 3 | CLI tool to interact with paperless-ngx remote API 4 | 5 | ## Subcommands 6 | 7 | - `upload`: Uploads local document(s) to Paperless instance. 8 | - `consume`: Consumes a local directory and uploads each file to Paperless instance. The files will be deleted once uploaded. 9 | - `bulk-download`: Downloads all documents at once. 10 | 11 | ## Installation 12 | 13 | Go: 14 | `go install github.com/ccremer/paperless-cli@latest` 15 | 16 | Docker: 17 | `docker run ghcr.io/ccremer/paperless-cli:latest` 18 | 19 | Binary: 20 | ```bash 21 | wget https://github.com/ccremer/paperless-cli/releases/latest/download/paperless-cli_linux_amd64 22 | chmod +x paperless-cli_linux_amd64 23 | sudo mv paperless-cli_linux_amd64 /usr/local/bin/paperless-cli 24 | ``` 25 | 26 | Deb: 27 | ```bash 28 | wget https://github.com/ccremer/paperless-cli/releases/latest/download/paperless-cli_linux_amd64.deb 29 | sudo dpkg -i paperless-cli_linux_amd64.deb 30 | rm paperless-cli_linux_amd64.deb 31 | ``` 32 | 33 | RPM: 34 | ```bash 35 | wget https://github.com/ccremer/paperless-cli/releases/latest/download/paperless-cli_linux_amd64.rpm 36 | sudo rpm -i paperless-cli_linux_amd64.rpm 37 | rm paperless-cli_linux_amd64.rpm 38 | ``` 39 | 40 | ## Systemd Service 41 | 42 | The `consume` subcommand is a long-running process that is best run as a daemon. 43 | The Deb/RPM packages come with a SystemD unit file. 44 | 45 | Enable SystemD `consume` service: 46 | ```bash 47 | sudo ${EDITOR:-nano} /etc/default/paperless-cli 48 | sudo systemctl enable paperless-consume 49 | sudo systemctl start paperless-consume 50 | ``` 51 | 52 | ## Configuration 53 | 54 | Most config options of each command can be specified as both CLI flag and as an environment variable. 55 | Run each command with `--help` to view the variables names (if supported). 56 | 57 | Additionally, some options can be specified in a YAML file. 58 | Run `init` subcommand to initialize a new config file with the supported options. 59 | 60 | ## Why does this exist? 61 | 62 | I didn't find any other projects or means to consume a directory that _uploads_ the documents via API. 63 | In my case, I can't configure the scanner to directly upload to the consume dir as setup by paperless-already, I have to watch the dir on a different host. 64 | So I created a tool that also watches a directory, but uploads them to Paperless instead. 65 | 66 | Other projects that I've found: 67 | 68 | - https://github.com/stgarf/paperless-cli (archived, doesn't upload or consume) 69 | 70 | ## Development 71 | 72 | ### Requirements 73 | 74 | - go 75 | - docker 76 | - docker-compose (if running local test instance of paperless-ngx) 77 | - goreleaser (if building deb/rpm packages locally) 78 | 79 | ### Build 80 | 81 | Run `go run . --help` to directly invoke the CLI for testing purposes. 82 | Run `make help` to see a list of available targets. 83 | 84 | Commonly used: 85 | 86 | - `make build`: Build the project 87 | - `make local-install`: Start paperless-ngx in docker-compose (`http://localhost:8008`, user `admin:admin`) 88 | -------------------------------------------------------------------------------- /upload_command.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/ccremer/paperless-cli/pkg/paperless" 8 | "github.com/ccremer/plogr" 9 | "github.com/go-logr/logr" 10 | "github.com/pterm/pterm" 11 | "github.com/urfave/cli/v2" 12 | ) 13 | 14 | type UploadCommand struct { 15 | cli.Command 16 | 17 | PaperlessURL string 18 | PaperlessToken string 19 | PaperlessUser string 20 | 21 | CreatedAt cli.Timestamp 22 | DocumentTitle string 23 | DocumentType string 24 | Correspondent string 25 | DocumentTags cli.StringSlice 26 | DeleteAfterUpload bool 27 | } 28 | 29 | func newUploadCommand() *UploadCommand { 30 | c := &UploadCommand{} 31 | c.Command = cli.Command{ 32 | Name: "upload", 33 | Usage: "Uploads local document(s) to Paperless instance", 34 | Before: before(func(ctx *cli.Context) error { 35 | if ctx.NArg() == 0 { 36 | ctx.Command.Subcommands = nil // required to print usage of subcommand 37 | _ = cli.ShowCommandHelp(ctx, ctx.Command.Name) 38 | return fmt.Errorf("At least one file is required") 39 | } 40 | return nil 41 | }, loadConfigFileFn), 42 | Action: actions(LogMetadata, c.Action), 43 | 44 | Flags: []cli.Flag{ 45 | newURLFlag(&c.PaperlessURL), 46 | newUsernameFlag(&c.PaperlessUser), 47 | newTokenFlag(&c.PaperlessToken), 48 | newCreatedAtFlag(&c.CreatedAt), 49 | newTitleFlag(&c.DocumentTitle), 50 | newDocumentTypeFlag(&c.DocumentType), 51 | newCorrespondentFlag(&c.Correspondent), 52 | newTagFlag(&c.DocumentTags), 53 | newDeleteAfterUploadFlag(&c.DeleteAfterUpload), 54 | }, 55 | ArgsUsage: "[FILES...]", 56 | } 57 | return c 58 | } 59 | 60 | func (c *UploadCommand) Action(ctx *cli.Context) error { 61 | log := logr.FromContextOrDiscard(ctx.Context) 62 | 63 | params := paperless.UploadParams{} 64 | 65 | if created := c.CreatedAt.Value(); created != nil { 66 | params.Created = *created 67 | log = log.WithValues("created", created.Format("2006-02-03")) 68 | } 69 | params.DocumentType, params.Title, params.Correspondent = c.DocumentType, c.DocumentTitle, c.Correspondent 70 | params.Tags = c.DocumentTags.Value() 71 | log = log.WithValues("title", params.Title, "type", params.DocumentType, "tags", params.Tags) 72 | 73 | clt := paperless.NewClient(c.PaperlessURL, c.PaperlessUser, c.PaperlessToken) 74 | for _, arg := range ctx.Args().Slice() { 75 | log.Info("Uploading file", "file", arg) 76 | err := clt.Upload(ctx.Context, arg, params) 77 | if err != nil { 78 | log.Error(err, "Could not upload file") 79 | continue 80 | } 81 | pterm.Success.Println(plogr.DefaultFormatter("File uploaded", map[string]interface{}{ 82 | "file": arg, 83 | })) 84 | if c.DeleteAfterUpload { 85 | c.deleteAfterUpload(arg) 86 | } 87 | } 88 | return nil 89 | } 90 | 91 | func (c *UploadCommand) deleteAfterUpload(arg string) { 92 | err := os.Remove(arg) 93 | if err != nil { 94 | pterm.Warning.Println(plogr.DefaultFormatter("File could not be deleted", map[string]interface{}{ 95 | "file": arg, 96 | "error": err, 97 | })) 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /pkg/paperless/upload.go: -------------------------------------------------------------------------------- 1 | package paperless 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "fmt" 7 | "io" 8 | "mime/multipart" 9 | "net/http" 10 | "os" 11 | "path/filepath" 12 | "time" 13 | 14 | "github.com/go-logr/logr" 15 | ) 16 | 17 | type UploadParams struct { 18 | Title string 19 | Created time.Time 20 | Correspondent string 21 | DocumentType string 22 | Tags []string 23 | } 24 | 25 | func (clt *Client) Upload(ctx context.Context, filePath string, params UploadParams) error { 26 | req, err := clt.makeFileUploadRequest(ctx, filePath, params) 27 | if err != nil { 28 | return err 29 | } 30 | 31 | resp, err := clt.HttpClient.Do(req) 32 | if err != nil { 33 | return fmt.Errorf("request failed: %w", err) 34 | } 35 | body, _ := io.ReadAll(resp.Body) 36 | errMessage := string(body) 37 | switch resp.StatusCode { 38 | case http.StatusOK: 39 | return nil 40 | case http.StatusUnauthorized: 41 | return fmt.Errorf("unauthorized") 42 | default: 43 | return fmt.Errorf("request failed with status code %d: %v", resp.StatusCode, errMessage) 44 | } 45 | } 46 | 47 | func (clt *Client) makeFileUploadRequest(ctx context.Context, filePath string, params UploadParams) (*http.Request, error) { 48 | log := logr.FromContextOrDiscard(ctx).WithValues("filePath", filePath) 49 | 50 | log.V(1).Info("Reading file") 51 | file, err := os.Open(filePath) 52 | if err != nil { 53 | return nil, fmt.Errorf("cannot read source file: %w", err) 54 | } 55 | defer file.Close() 56 | 57 | log.V(1).Info("Preparing payload for file upload") 58 | body := &bytes.Buffer{} 59 | writer := multipart.NewWriter(body) 60 | part, err := writer.CreateFormFile("document", filepath.Base(filePath)) 61 | if err != nil { 62 | return nil, fmt.Errorf("cannot prepare file for upload: %w", err) 63 | } 64 | _, err = io.Copy(part, file) 65 | if err != nil { 66 | return nil, fmt.Errorf("cannot copy file to request: %w", err) 67 | } 68 | 69 | writeUploadFormFields(writer, params) 70 | 71 | err = writer.Close() 72 | if err != nil { 73 | return nil, fmt.Errorf("cannot write form body: %w", err) 74 | } 75 | 76 | log.V(1).Info("Preparing request") 77 | req, err := http.NewRequestWithContext(ctx, "POST", clt.URL+"/api/documents/post_document/", body) 78 | if err != nil { 79 | return nil, fmt.Errorf("cannot prepare request: %w", err) 80 | } 81 | clt.setAuth(req) 82 | req.Header.Set("Content-Type", writer.FormDataContentType()) 83 | return req, nil 84 | } 85 | 86 | func writeUploadFormFields(writer *multipart.Writer, params UploadParams) { 87 | if !params.Created.IsZero() { 88 | _ = writer.WriteField("created", params.Created.Format("2006-01-02")) 89 | } 90 | if v, f := params.Correspondent, "correspondent"; v != "" { 91 | _ = writer.WriteField(f, v) 92 | } 93 | if v, f := params.Title, "title"; v != "" { 94 | _ = writer.WriteField(f, v) 95 | } 96 | if v, f := params.DocumentType, "document_type"; v != "" { 97 | _ = writer.WriteField(f, v) 98 | } 99 | for _, tag := range params.Tags { 100 | _ = writer.WriteField("tags", tag) // we can specify multiple times 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /pkg/paperless/query.go: -------------------------------------------------------------------------------- 1 | package paperless 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "net/url" 10 | "reflect" 11 | "strconv" 12 | 13 | "github.com/go-logr/logr" 14 | ) 15 | 16 | type QueryParams struct { 17 | TruncateContent bool `param:"truncate_content"` 18 | Ordering string `param:"ordering"` 19 | PageSize int64 `param:"page_size"` 20 | page int64 `param:"page"` 21 | } 22 | 23 | type QueryResult struct { 24 | Results []Document `json:"results,omitempty"` 25 | Next string `json:"next,omitempty"` 26 | } 27 | 28 | // NextPage returns the next page number for pagination. 29 | // It returns 1 if QueryResult.Next is empty (first page), or 0 if there's an error parsing QueryResult.Next. 30 | func (r QueryResult) NextPage() int64 { 31 | if r.Next == "" { 32 | return 1 // first page 33 | } 34 | values, err := url.ParseQuery(r.Next) 35 | if err != nil { 36 | return 0 37 | } 38 | raw := values.Get("page") 39 | page, err := strconv.ParseInt(raw, 10, 64) 40 | if err != nil { 41 | return 0 42 | } 43 | return page 44 | } 45 | 46 | func (clt *Client) QueryDocuments(ctx context.Context, params QueryParams) ([]Document, error) { 47 | documents := make([]Document, 0) 48 | params.page = 1 49 | for i := int64(0); i < params.page; i++ { 50 | result, err := clt.queryDocumentsInPage(ctx, params) 51 | if err != nil { 52 | return nil, err 53 | } 54 | params.page = result.NextPage() 55 | documents = append(documents, result.Results...) 56 | } 57 | return documents, nil 58 | } 59 | 60 | func (clt *Client) makeQueryRequest(ctx context.Context, params QueryParams) (*http.Request, error) { 61 | log := logr.FromContextOrDiscard(ctx) 62 | 63 | values := paramsToValues(params) 64 | 65 | path := clt.URL + "/api/documents/?" + values.Encode() 66 | log.V(1).Info("Preparing request", "path", path) 67 | req, err := http.NewRequestWithContext(ctx, "GET", path, nil) 68 | if err != nil { 69 | return nil, fmt.Errorf("cannot prepare request: %w", err) 70 | } 71 | clt.setAuth(req) 72 | req.Header.Set("Content-Type", "application/json") 73 | return req, nil 74 | } 75 | 76 | func (clt *Client) queryDocumentsInPage(ctx context.Context, params QueryParams) (*QueryResult, error) { 77 | req, err := clt.makeQueryRequest(ctx, params) 78 | if err != nil { 79 | return nil, err 80 | } 81 | 82 | log := logr.FromContextOrDiscard(ctx) 83 | log.V(1).Info("Awaiting response") 84 | resp, err := clt.HttpClient.Do(req) 85 | if err != nil { 86 | return nil, fmt.Errorf("request failed: %w", err) 87 | } 88 | defer resp.Body.Close() 89 | 90 | b, err := io.ReadAll(resp.Body) 91 | if err != nil { 92 | return nil, fmt.Errorf("cannot read body: %w", err) 93 | } 94 | log.V(2).Info("Read response", "body", string(b)) 95 | if resp.StatusCode != http.StatusOK { 96 | return nil, fmt.Errorf("request failed: %s: %s", resp.Status, string(b)) 97 | } 98 | 99 | result := QueryResult{} 100 | parseErr := json.Unmarshal(b, &result) 101 | if parseErr != nil { 102 | return nil, fmt.Errorf("cannot parse JSON: %w", parseErr) 103 | } 104 | log.V(1).Info("Parsed response", "result", result) 105 | return &result, nil 106 | } 107 | 108 | func paramsToValues(params QueryParams) url.Values { 109 | values := url.Values{} 110 | typ := reflect.TypeOf(params) 111 | value := reflect.ValueOf(params) 112 | for i := 0; i < typ.NumField(); i++ { 113 | structField := typ.Field(i) 114 | tag := structField.Tag.Get("param") 115 | field := value.Field(i) 116 | paramValue := "" 117 | switch field.Kind() { 118 | case reflect.Bool: 119 | paramValue = strconv.FormatBool(field.Bool()) 120 | case reflect.String: 121 | paramValue = field.String() 122 | case reflect.Int64: 123 | paramValue = strconv.FormatInt(field.Int(), 10) 124 | default: 125 | panic(fmt.Errorf("not implemented type: %s", field.Kind())) 126 | } 127 | values.Set(tag, paramValue) 128 | } 129 | return values 130 | } 131 | -------------------------------------------------------------------------------- /flags.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "strings" 7 | "time" 8 | 9 | "github.com/ccremer/paperless-cli/pkg/paperless" 10 | "github.com/urfave/cli/v2" 11 | "github.com/urfave/cli/v2/altsrc" 12 | ) 13 | 14 | func newConfigFileFlag() *cli.StringFlag { 15 | return &cli.StringFlag{ 16 | Name: "config", EnvVars: []string{"CONFIG"}, 17 | Aliases: []string{"C"}, 18 | Value: "config.yaml", 19 | Usage: "path to a config file containing additional config.", 20 | } 21 | } 22 | 23 | func newLogLevelFlag() *altsrc.IntFlag { 24 | return altsrc.NewIntFlag(&cli.IntFlag{ 25 | Name: "log-level", Aliases: []string{"v"}, EnvVars: []string{"LOG_LEVEL"}, 26 | Usage: "number of the log level verbosity", 27 | Value: 0, 28 | }) 29 | } 30 | 31 | func newURLFlag(dest *string) *altsrc.StringFlag { 32 | return altsrc.NewStringFlag(&cli.StringFlag{ 33 | Name: "url", EnvVars: envVars("URL"), 34 | Usage: "URL endpoint of the paperless instance.", 35 | Action: checkEmptyString("url"), 36 | Destination: dest, 37 | }) 38 | } 39 | 40 | func newTokenFlag(dest *string) *altsrc.StringFlag { 41 | return altsrc.NewStringFlag(&cli.StringFlag{ 42 | Name: "token", EnvVars: envVars("TOKEN"), 43 | Usage: "password or token of the paperless instance.", 44 | Action: checkEmptyString("token"), 45 | Destination: dest, 46 | }) 47 | } 48 | 49 | func newUsernameFlag(dest *string) *altsrc.StringFlag { 50 | return altsrc.NewStringFlag(&cli.StringFlag{ 51 | Name: "username", EnvVars: envVars("USERNAME"), 52 | Usage: "username for BasicAuth of the paperless instance. Leave empty to use token authentication.", 53 | Destination: dest, 54 | }) 55 | } 56 | 57 | func newCreatedAtFlag(dest *cli.Timestamp) *cli.TimestampFlag { 58 | return &cli.TimestampFlag{ 59 | Name: "created-at", 60 | Usage: `set the "created" date for all given files.`, 61 | Layout: "2006-01-02", 62 | Destination: dest, 63 | } 64 | } 65 | 66 | func newTitleFlag(dest *string) *cli.StringFlag { 67 | return &cli.StringFlag{ 68 | Name: "title", 69 | Usage: "set the document title for all given files.", 70 | Destination: dest, 71 | } 72 | } 73 | func newCorrespondentFlag(dest *string) *cli.StringFlag { 74 | return &cli.StringFlag{ 75 | Name: "correspondent", 76 | Usage: "set the correspondent for all given files.", 77 | Destination: dest, 78 | } 79 | } 80 | func newDocumentTypeFlag(dest *string) *cli.StringFlag { 81 | return &cli.StringFlag{ 82 | Name: "type", 83 | Usage: "set the document type for all given files.", 84 | Destination: dest, 85 | } 86 | } 87 | func newTagFlag(dest *cli.StringSlice) *cli.StringSliceFlag { 88 | return &cli.StringSliceFlag{ 89 | Name: "tag", 90 | Usage: "set the document tag(s) for all given files.", 91 | Destination: dest, 92 | } 93 | } 94 | 95 | func newDeleteAfterUploadFlag(dest *bool) *cli.BoolFlag { 96 | return &cli.BoolFlag{ 97 | Name: "delete-after-upload", EnvVars: envVars("DELETE_AFTER_UPLOAD"), 98 | Usage: "deletes the file(s) after upload", 99 | Destination: dest, 100 | } 101 | } 102 | 103 | func newConsumeDirFlag(dest *string) *altsrc.StringFlag { 104 | return altsrc.NewStringFlag(&cli.StringFlag{ 105 | Name: "consume-dir", EnvVars: []string{"CONSUME_DIR"}, 106 | Usage: "the directory name which to consume files.", 107 | Required: true, 108 | Destination: dest, 109 | Action: checkEmptyString("consume-dir"), 110 | }) 111 | } 112 | 113 | func newConsumeDelayFlag(dest *time.Duration) *altsrc.DurationFlag { 114 | return altsrc.NewDurationFlag(&cli.DurationFlag{ 115 | Name: "consume-delay", EnvVars: []string{"CONSUME_DELAY"}, 116 | Usage: "the delay after detecting the last file write operation before uploading it.", 117 | Value: 1 * time.Second, 118 | Destination: dest, 119 | Action: func(ctx *cli.Context, duration time.Duration) error { 120 | if duration.Milliseconds() < 100 { 121 | return showFlagError(ctx, fmt.Errorf("Duration of flag %q must be at least 100ms", "consume-delay")) 122 | } 123 | return nil 124 | }, 125 | }) 126 | } 127 | 128 | func newTargetPathFlag(dest *string) *altsrc.StringFlag { 129 | return altsrc.NewStringFlag(&cli.StringFlag{ 130 | Name: "target-path", EnvVars: []string{"DOWNLOAD_TARGET_PATH"}, 131 | Usage: "target file path where documents are downloaded.", 132 | DefaultText: "documents.zip", 133 | Destination: dest, 134 | }) 135 | } 136 | 137 | func newDownloadContentFlag(dest *string) *altsrc.StringFlag { 138 | return altsrc.NewStringFlag(&cli.StringFlag{ 139 | Name: "content", EnvVars: []string{"DOWNLOAD_CONTENT"}, 140 | Usage: "selection of document variant.", 141 | Value: paperless.BulkDownloadArchives.String(), 142 | Destination: dest, 143 | Action: func(ctx *cli.Context, s string) error { 144 | enum := []string{ 145 | paperless.BulkDownloadArchives.String(), 146 | paperless.BulkDownloadOriginal.String(), 147 | paperless.BulkDownloadBoth.String()} 148 | for _, key := range enum { 149 | if s == key { 150 | return nil 151 | } 152 | } 153 | return fmt.Errorf("parameter %q must be one of [%s]", "content", strings.Join(enum, ", ")) 154 | }, 155 | }) 156 | } 157 | 158 | func newUnzipFlag(dest *bool) *altsrc.BoolFlag { 159 | return altsrc.NewBoolFlag(&cli.BoolFlag{ 160 | Name: "unzip", EnvVars: []string{"DOWNLOAD_UNZIP"}, 161 | Usage: "unzip the downloaded file.", 162 | Destination: dest, 163 | }) 164 | } 165 | 166 | func newOverwriteFlag(dest *bool) *altsrc.BoolFlag { 167 | return altsrc.NewBoolFlag(&cli.BoolFlag{ 168 | Name: "overwrite", EnvVars: []string{"DOWNLOAD_OVERWRITE"}, 169 | Usage: "deletes existing file(s) before downloading.", 170 | Destination: dest, 171 | }) 172 | } 173 | 174 | func newIncrementalFlag(dest *bool) *altsrc.BoolFlag { 175 | return altsrc.NewBoolFlag(&cli.BoolFlag{ 176 | Name: "incremental", EnvVars: []string{"DOWNLOAD_INCREMENTAL"}, 177 | Usage: fmt.Sprintf("only download the missing files and remove deleted documents. Implies --%s and --%s", 178 | newUnzipFlag(nil).Name, newOverwriteFlag(nil).Name), 179 | Destination: dest, 180 | }) 181 | } 182 | 183 | func loadConfigFileFn(ctx *cli.Context) error { 184 | path := ctx.String(newConfigFileFlag().Name) 185 | flags := ctx.Command.Flags 186 | if _, err := os.Stat(path); err != nil && os.IsNotExist(err) { 187 | return nil 188 | } 189 | return altsrc.InitInputSourceWithContext(flags, altsrc.NewYamlSourceFromFlagFunc(newConfigFileFlag().Name))(ctx) 190 | } 191 | 192 | func checkEmptyString(flagName string) func(*cli.Context, string) error { 193 | return func(ctx *cli.Context, s string) error { 194 | if s == "" { 195 | return showFlagError(ctx, fmt.Errorf(`Required flag %q not set`, flagName)) 196 | } 197 | return nil 198 | } 199 | } 200 | 201 | func showFlagError(ctx *cli.Context, err error) error { 202 | subcommands := ctx.Command.Subcommands 203 | ctx.Command.Subcommands = nil // required to print usage of subcommand 204 | _ = cli.ShowCommandHelp(ctx, ctx.Command.Name) 205 | ctx.Command.Subcommands = subcommands 206 | return err 207 | } 208 | -------------------------------------------------------------------------------- /bulk_download_command.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/fs" 6 | "os" 7 | "path/filepath" 8 | 9 | "github.com/ccremer/paperless-cli/pkg/archive" 10 | "github.com/ccremer/paperless-cli/pkg/errors" 11 | "github.com/ccremer/paperless-cli/pkg/localdb" 12 | "github.com/ccremer/paperless-cli/pkg/paperless" 13 | "github.com/go-logr/logr" 14 | "github.com/urfave/cli/v2" 15 | ) 16 | 17 | type BulkDownloadCommand struct { 18 | cli.Command 19 | 20 | PaperlessURL string 21 | PaperlessToken string 22 | PaperlessUser string 23 | 24 | TargetPath string 25 | Content string 26 | UnzipEnabled bool 27 | OverwriteExistingTarget bool 28 | Incremental bool 29 | } 30 | 31 | const desc = `Use this command to create a local offline-copy of all documents. 32 | If --%s is given, it will only download documents that don't exist locally, to save bandwidth.` 33 | 34 | func newBulkDownloadCommand() *BulkDownloadCommand { 35 | c := &BulkDownloadCommand{} 36 | c.Command = cli.Command{ 37 | Name: "bulk-download", 38 | Usage: "Downloads all documents at once", 39 | Description: fmt.Sprintf(desc, newIncrementalFlag(nil).Name), 40 | Before: loadConfigFileFn, 41 | Action: actions(LogMetadata, c.Action), 42 | Flags: []cli.Flag{ 43 | newURLFlag(&c.PaperlessURL), 44 | newUsernameFlag(&c.PaperlessUser), 45 | newTokenFlag(&c.PaperlessToken), 46 | newTargetPathFlag(&c.TargetPath), 47 | newDownloadContentFlag(&c.Content), 48 | newUnzipFlag(&c.UnzipEnabled), 49 | newOverwriteFlag(&c.OverwriteExistingTarget), 50 | newIncrementalFlag(&c.Incremental), 51 | }, 52 | } 53 | return c 54 | } 55 | 56 | func (c *BulkDownloadCommand) Action(ctx *cli.Context) error { 57 | log := logr.FromContextOrDiscard(ctx.Context) 58 | if c.Incremental { 59 | c.OverwriteExistingTarget = true 60 | c.UnzipEnabled = true 61 | } 62 | 63 | if prepareErr := c.prepareTarget(); prepareErr != nil { 64 | return prepareErr 65 | } 66 | clt := paperless.NewClient(c.PaperlessURL, c.PaperlessUser, c.PaperlessToken) 67 | 68 | log.Info("Getting list of documents") 69 | documents, queryErr := clt.QueryDocuments(ctx.Context, paperless.QueryParams{ 70 | TruncateContent: true, 71 | Ordering: "id", 72 | PageSize: 100, 73 | }) 74 | if queryErr != nil { 75 | return queryErr 76 | } 77 | documentIDs := paperless.MapToDocumentIDs(documents) 78 | var db *localdb.Database 79 | 80 | if c.Incremental { 81 | log.V(1).Info("Opening DB", "dir", c.getTargetPath()) 82 | newDb, openErr := localdb.Open(c.getTargetPath()) 83 | if openErr != nil { 84 | return openErr 85 | } 86 | db = newDb 87 | newDocuments := c.filterMissingDocuments(db, documents) 88 | for _, doc := range newDocuments { 89 | db.Put(doc) 90 | } 91 | 92 | deletedDocuments := c.filterDeletedDocuments(db, paperless.MapToDocumentMap(documents)) 93 | for _, deletedDoc := range deletedDocuments { 94 | db.Remove(deletedDoc) 95 | } 96 | if err := c.removeFiles(ctx, deletedDocuments); err != nil { 97 | return fmt.Errorf("cannot delete local documents: %w", err) 98 | } 99 | log.Info("Cleaned up deleted documents", "count", len(deletedDocuments)) 100 | documentIDs = paperless.MapToDocumentIDs(newDocuments) 101 | } 102 | 103 | if len(documentIDs) == 0 { 104 | log.Info("Nothing to download") 105 | if db != nil { 106 | log.V(1).Info("Saving DB") 107 | return db.Close() 108 | } 109 | return nil 110 | } 111 | 112 | tmpFile, err := c.downloadDocuments(ctx, clt, documentIDs) 113 | if err != nil { 114 | return err 115 | } 116 | defer os.Remove(tmpFile.Name()) // cleanup if not renamed 117 | 118 | if c.UnzipEnabled { 119 | unzipErr := c.unzip(ctx, tmpFile) 120 | if unzipErr != nil { 121 | return unzipErr 122 | } 123 | if db == nil { 124 | return nil 125 | } 126 | log.V(1).Info("Saving DB") 127 | return db.Close() 128 | } 129 | return c.move(ctx, tmpFile) 130 | } 131 | 132 | func (c *BulkDownloadCommand) removeFiles(ctx *cli.Context, deletedDocs []paperless.Document) error { 133 | log := logr.FromContextOrDiscard(ctx.Context) 134 | 135 | dir := c.getTargetPath() 136 | 137 | files := map[string]paperless.Document{} 138 | for _, doc := range deletedDocs { 139 | files[doc.ArchivedFileName] = doc 140 | files[doc.OriginalFileName] = doc 141 | } 142 | 143 | err := filepath.WalkDir(dir, func(path string, entry fs.DirEntry, err error) error { 144 | if err != nil { 145 | return err 146 | } 147 | if entry.IsDir() { 148 | return nil 149 | } 150 | fileName := filepath.Base(path) 151 | if doc, found := files[fileName]; found { 152 | log.V(1).Info("Removing deleted document", "id", doc.ID, "path", path) 153 | _ = os.Remove(path) 154 | } 155 | return nil 156 | }) 157 | return err 158 | } 159 | 160 | func (c *BulkDownloadCommand) downloadDocuments(ctx *cli.Context, clt *paperless.Client, documentIDs []int) (*os.File, error) { 161 | log := logr.FromContextOrDiscard(ctx.Context) 162 | 163 | tmpFile, createTempErr := os.CreateTemp(os.TempDir(), "paperless-bulk-download-") 164 | if createTempErr != nil { 165 | return nil, fmt.Errorf("cannot open temporary file: %w", createTempErr) 166 | } 167 | 168 | log.Info("Downloading documents", "count", len(documentIDs)) 169 | downloadErr := clt.BulkDownload(ctx.Context, tmpFile, paperless.BulkDownloadParams{ 170 | FollowFormatting: true, 171 | Content: paperless.BulkDownloadContent(c.Content), 172 | DocumentIDs: documentIDs, 173 | }) 174 | return tmpFile, errors.Wrap(downloadErr, "could not download documents") 175 | } 176 | 177 | func (c *BulkDownloadCommand) unzip(ctx *cli.Context, tmpFile *os.File) error { 178 | log := logr.FromContextOrDiscard(ctx.Context) 179 | downloadFilePath := c.getTargetPath() 180 | if c.Content == paperless.BulkDownloadArchives.String() { 181 | downloadFilePath = filepath.Join(downloadFilePath, paperless.BulkDownloadArchives.String()) 182 | } 183 | if c.Content == paperless.BulkDownloadOriginal.String() { 184 | downloadFilePath = filepath.Join(downloadFilePath, paperless.BulkDownloadOriginal.String()) 185 | } 186 | if unzipErr := archive.Unzip(ctx.Context, tmpFile.Name(), downloadFilePath); unzipErr != nil { 187 | return fmt.Errorf("cannot unzip file %q to %q: %w", tmpFile.Name(), downloadFilePath, unzipErr) 188 | } 189 | log.Info("Unzipped archive to dir", "dir", downloadFilePath) 190 | return nil 191 | } 192 | 193 | func (c *BulkDownloadCommand) move(ctx *cli.Context, tmpFile *os.File) error { 194 | log := logr.FromContextOrDiscard(ctx.Context) 195 | downloadFilePath := c.getTargetPath() 196 | if renameErr := os.Rename(tmpFile.Name(), downloadFilePath); renameErr != nil { 197 | return fmt.Errorf("cannot move temp file: %w", renameErr) 198 | } 199 | log.Info("Downloaded zip archive", "file", downloadFilePath) 200 | return nil 201 | } 202 | 203 | func (c *BulkDownloadCommand) getTargetPath() string { 204 | if c.TargetPath != "" { 205 | return c.TargetPath 206 | } 207 | if c.UnzipEnabled { 208 | return "documents" 209 | } 210 | return "documents.zip" 211 | } 212 | 213 | func (c *BulkDownloadCommand) prepareTarget() error { 214 | target := c.getTargetPath() 215 | if c.OverwriteExistingTarget { 216 | if c.Incremental { 217 | return nil 218 | } 219 | return os.RemoveAll(target) 220 | } 221 | _, err := os.Stat(target) 222 | if err != nil && os.IsNotExist(err) { 223 | return nil 224 | } 225 | return fmt.Errorf("target %q exists, abort", target) 226 | } 227 | 228 | func (c *BulkDownloadCommand) filterMissingDocuments(db *localdb.Database, documentsOnServer []paperless.Document) []paperless.Document { 229 | missing := make([]paperless.Document, 0) 230 | for i := 0; i < len(documentsOnServer); i++ { 231 | serverDoc := documentsOnServer[i] 232 | localDoc := db.FindByID(serverDoc.ID) 233 | if localDoc == nil { 234 | missing = append(missing, serverDoc) 235 | } 236 | } 237 | return missing 238 | } 239 | 240 | func (c *BulkDownloadCommand) filterDeletedDocuments(db *localdb.Database, documentsOnServer map[int]paperless.Document) []paperless.Document { 241 | extra := make([]paperless.Document, 0) 242 | allLocalDocs := db.GetAll() 243 | for i := 0; i < len(allLocalDocs); i++ { 244 | localDoc := allLocalDocs[i] 245 | if _, found := documentsOnServer[localDoc.ID]; !found { 246 | extra = append(extra, localDoc) 247 | } 248 | } 249 | return extra 250 | } 251 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | atomicgo.dev/assert v0.0.2 h1:FiKeMiZSgRrZsPo9qn/7vmr7mCsh5SZyXY4YGYiYwrg= 2 | atomicgo.dev/assert v0.0.2/go.mod h1:ut4NcI3QDdJtlmAxQULOmA13Gz6e2DWbSAS8RUOmNYQ= 3 | atomicgo.dev/cursor v0.1.1/go.mod h1:Lr4ZJB3U7DfPPOkbH7/6TOtJ4vFGHlgj1nc+n900IpU= 4 | atomicgo.dev/cursor v0.2.0 h1:H6XN5alUJ52FZZUkI7AlJbUc1aW38GWZalpYRPpoPOw= 5 | atomicgo.dev/cursor v0.2.0/go.mod h1:Lr4ZJB3U7DfPPOkbH7/6TOtJ4vFGHlgj1nc+n900IpU= 6 | atomicgo.dev/keyboard v0.2.8/go.mod h1:BC4w9g00XkxH/f1HXhW2sXmJFOCWbKn9xrOunSFtExQ= 7 | atomicgo.dev/keyboard v0.2.9 h1:tOsIid3nlPLZ3lwgG8KZMp/SFmr7P0ssEN5JUsm78K8= 8 | atomicgo.dev/keyboard v0.2.9/go.mod h1:BC4w9g00XkxH/f1HXhW2sXmJFOCWbKn9xrOunSFtExQ= 9 | atomicgo.dev/schedule v0.1.0 h1:nTthAbhZS5YZmgYbb2+DH8uQIZcTlIrd4eYr3UQxEjs= 10 | atomicgo.dev/schedule v0.1.0/go.mod h1:xeUa3oAkiuHYh8bKiQBRojqAMq3PXXbJujjb0hw8pEU= 11 | github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= 12 | github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= 13 | github.com/MarvinJWendt/testza v0.1.0/go.mod h1:7AxNvlfeHP7Z/hDQ5JtE3OKYT3XFUeLCDE2DQninSqs= 14 | github.com/MarvinJWendt/testza v0.2.1/go.mod h1:God7bhG8n6uQxwdScay+gjm9/LnO4D3kkcZX4hv9Rp8= 15 | github.com/MarvinJWendt/testza v0.2.8/go.mod h1:nwIcjmr0Zz+Rcwfh3/4UhBp7ePKVhuBExvZqnKYWlII= 16 | github.com/MarvinJWendt/testza v0.2.10/go.mod h1:pd+VWsoGUiFtq+hRKSU1Bktnn+DMCSrDrXDpX2bG66k= 17 | github.com/MarvinJWendt/testza v0.2.12/go.mod h1:JOIegYyV7rX+7VZ9r77L/eH6CfJHHzXjB69adAhzZkI= 18 | github.com/MarvinJWendt/testza v0.3.0/go.mod h1:eFcL4I0idjtIx8P9C6KkAuLgATNKpX4/2oUqKc6bF2c= 19 | github.com/MarvinJWendt/testza v0.4.2/go.mod h1:mSdhXiKH8sg/gQehJ63bINcCKp7RtYewEjXsvsVUPbE= 20 | github.com/MarvinJWendt/testza v0.4.3/go.mod h1:CpXaOfceNEYnLDtNIyTrPPcCpDJYqzZnu2aiA2Wp33U= 21 | github.com/MarvinJWendt/testza v0.5.1/go.mod h1:L7csM8IBqCc0HH4TRYZSPCIRg6zJeqzM1pm3FSYZBso= 22 | github.com/MarvinJWendt/testza v0.5.2 h1:53KDo64C1z/h/d/stCYCPY69bt/OSwjq5KpFNwi+zB4= 23 | github.com/MarvinJWendt/testza v0.5.2/go.mod h1:xu53QFE5sCdjtMCKk8YMQ2MnymimEctc4n3EjyIYvEY= 24 | github.com/atomicgo/cursor v0.0.1/go.mod h1:cBON2QmmrysudxNBFthvMtN32r3jxVRIvzkUiF/RuIk= 25 | github.com/ccremer/plogr v0.7.0 h1:hASyuM8NYBfYclNHNdugrnHzLiPqFGt+zcMjpc0vdUA= 26 | github.com/ccremer/plogr v0.7.0/go.mod h1:57bEBtEjCiSqybkPwKbUYm7tbN7MmorYIK6DBwmmHIc= 27 | github.com/containerd/console v1.0.3 h1:lIr7SlA5PxZyMV30bDW0MGbiOPXwc63yRuCP0ARubLw= 28 | github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= 29 | github.com/cpuguy83/go-md2man/v2 v2.0.3 h1:qMCsGGgs+MAzDFyp9LpAe1Lqy/fY/qCovCm0qnXZOBM= 30 | github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= 31 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 32 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 33 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 34 | github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= 35 | github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= 36 | github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= 37 | github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= 38 | github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= 39 | github.com/gookit/color v1.4.2/go.mod h1:fqRyamkC1W8uxl+lxCQxOT09l/vYfZ+QeiX3rKQHCoQ= 40 | github.com/gookit/color v1.5.0/go.mod h1:43aQb+Zerm/BWh2GnrgOQm7ffz7tvQXEKV6BFMl7wAo= 41 | github.com/gookit/color v1.5.2/go.mod h1:w8h4bGiHeeBpvQVePTutdbERIUf3oJE5lZ8HM0UgXyg= 42 | github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= 43 | github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= 44 | github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= 45 | github.com/klauspost/cpuid/v2 v2.0.10/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= 46 | github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c= 47 | github.com/klauspost/cpuid/v2 v2.1.0/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= 48 | github.com/klauspost/cpuid/v2 v2.2.0/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= 49 | github.com/klauspost/cpuid/v2 v2.2.3 h1:sxCkb+qR91z4vsqw4vGGZlDgPz3G7gjaLyK3V8y70BU= 50 | github.com/klauspost/cpuid/v2 v2.2.3/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= 51 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= 52 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 53 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 54 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 55 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 56 | github.com/lithammer/fuzzysearch v1.1.5/go.mod h1:1R1LRNk7yKid1BaQkmuLQaHruxcC4HmAH30Dh61Ih1Q= 57 | github.com/lithammer/fuzzysearch v1.1.8 h1:/HIuJnjHuXS8bKaiTMeeDlW2/AyIWk2brx1V8LFgLN4= 58 | github.com/lithammer/fuzzysearch v1.1.8/go.mod h1:IdqeyBClc3FFqSzYq/MXESsS4S0FsZ5ajtkr5xPLts4= 59 | github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 60 | github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 61 | github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= 62 | github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 63 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 64 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 65 | github.com/pterm/pterm v0.12.27/go.mod h1:PhQ89w4i95rhgE+xedAoqous6K9X+r6aSOI2eFF7DZI= 66 | github.com/pterm/pterm v0.12.29/go.mod h1:WI3qxgvoQFFGKGjGnJR849gU0TsEOvKn5Q8LlY1U7lg= 67 | github.com/pterm/pterm v0.12.30/go.mod h1:MOqLIyMOgmTDz9yorcYbcw+HsgoZo3BQfg2wtl3HEFE= 68 | github.com/pterm/pterm v0.12.31/go.mod h1:32ZAWZVXD7ZfG0s8qqHXePte42kdz8ECtRyEejaWgXU= 69 | github.com/pterm/pterm v0.12.33/go.mod h1:x+h2uL+n7CP/rel9+bImHD5lF3nM9vJj80k9ybiiTTE= 70 | github.com/pterm/pterm v0.12.36/go.mod h1:NjiL09hFhT/vWjQHSj1athJpx6H8cjpHXNAK5bUw8T8= 71 | github.com/pterm/pterm v0.12.40/go.mod h1:ffwPLwlbXxP+rxT0GsgDTzS3y3rmpAO1NMjUkGTYf8s= 72 | github.com/pterm/pterm v0.12.49/go.mod h1:D4OBoWNqAfXkm5QLTjIgjNiMXPHemLJHnIreGUsWzWg= 73 | github.com/pterm/pterm v0.12.51/go.mod h1:79BLm4vos2z+eOoHnDG7ZWuYtLaSStyaspKjGmSoxc4= 74 | github.com/pterm/pterm v0.12.79 h1:lH3yrYMhdpeqX9y5Ep1u7DejyHy7NSQg9qrBjF9dFT4= 75 | github.com/pterm/pterm v0.12.79/go.mod h1:1v/gzOF1N0FsjbgTHZ1wVycRkKiatFvJSJC4IGaQAAo= 76 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 77 | github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= 78 | github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 79 | github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= 80 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 81 | github.com/sergi/go-diff v1.2.0 h1:XU+rvMAioB0UC3q1MFrIQy4Vo5/4VsRDQQXHsEya6xQ= 82 | github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= 83 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 84 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 85 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 86 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 87 | github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 88 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 89 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 90 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 91 | github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= 92 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 93 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 94 | github.com/urfave/cli/v2 v2.27.1 h1:8xSQ6szndafKVRmfyeUMxkNUJQMjL1F2zmsZ+qHpfho= 95 | github.com/urfave/cli/v2 v2.27.1/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ= 96 | github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= 97 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no= 98 | github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= 99 | github.com/xrash/smetrics v0.0.0-20231213231151-1d8dd44e695e h1:+SOyEddqYF09QP7vr7CgJ1eti3pY9Fn3LHO1M1r/0sI= 100 | github.com/xrash/smetrics v0.0.0-20231213231151-1d8dd44e695e/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= 101 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 102 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 103 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= 104 | golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E= 105 | golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= 106 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= 107 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= 108 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 109 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= 110 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= 111 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= 112 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 113 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 114 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 115 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 116 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 117 | golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 118 | golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 119 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 120 | golang.org/x/sys v0.0.0-20211013075003-97ac67df715c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 121 | golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 122 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 123 | golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 124 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 125 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 126 | golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= 127 | golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= 128 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 129 | golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 130 | golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 131 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 132 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= 133 | golang.org/x/term v0.16.0 h1:m+B6fahuftsE9qjo0VWp2FW0mB3MTJvR0BaMQrq0pmE= 134 | golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= 135 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 136 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 137 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= 138 | golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 139 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= 140 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 141 | golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= 142 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= 143 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 144 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 145 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= 146 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= 147 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 148 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 149 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= 150 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 151 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 152 | gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 153 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 154 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 155 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 156 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 157 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------