From ae7e95f4b0c01b885dedab684d8c9c7e91df280d Mon Sep 17 00:00:00 2001 From: Mateusz Hawrus Date: Mon, 6 Nov 2023 21:29:57 +0100 Subject: [PATCH] initial commit --- .github/CODEOWNERS | 1 + .github/renovate.json5 | 30 + .github/workflows/ci.yml | 43 ++ .github/workflows/release.yml | 25 + .github/workflows/scan.yml | 24 + .gitignore | 27 + .gitmodules | 9 + .golangci.yml | 91 +++ .gorelaser.yml | 24 + LICENSE | 674 ++++++++++++++++++ Makefile | 180 +++++ README.md | 181 +++++ bin/.keep | 0 builder.go | 71 ++ cmd/flags.go | 108 +++ cmd/main.go | 171 +++++ cmd/usage.txt | 40 ++ command.go | 215 ++++++ command_test.go | 185 +++++ cspell.yaml | 39 + go.mod | 21 + go.sum | 26 + internal/cache.go | 170 +++++ internal/deps_dev.go | 57 ++ internal/go_list.go | 104 +++ internal/go_proxy.go | 146 ++++ internal/module.go | 77 ++ output.go | 149 ++++ package.json | 13 + scripts/check-formatting.sh | 27 + scripts/check-trailing-whitespaces.bash | 20 + scripts/ensure_installed.sh | 23 + scripts/format-cspell-config.js | 30 + scripts/makefile-help.awk | 18 + source.go | 89 +++ test/bats | 1 + test/inputs/generate_responses.sh | 55 ++ test/inputs/go.mod | 14 + test/inputs/go.sum | 6 + test/inputs/responses.json | 229 ++++++ test/outputs/all_details_for_all_dependencies | 7 + test/outputs/basic_usage | 5 + test/outputs/modules_cache | 5 + test/outputs/output.csv | 5 + test/outputs/output.json | 49 ++ test/outputs/show_indirect | 7 + test/outputs/show_releases | 5 + test/outputs/show_versions | 5 + test/outputs/skip_fresh | 4 + test/outputs/skip_fresh_show_indirect | 6 + test/test.bats | 221 ++++++ test/test_helper/bats-assert | 1 + test/test_helper/bats-support | 1 + test/test_server.go | 62 ++ 54 files changed, 3796 insertions(+) create mode 100644 .github/CODEOWNERS create mode 100644 .github/renovate.json5 create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/scan.yml create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 .golangci.yml create mode 100644 .gorelaser.yml create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 bin/.keep create mode 100644 builder.go create mode 100644 cmd/flags.go create mode 100644 cmd/main.go create mode 100644 cmd/usage.txt create mode 100644 command.go create mode 100644 command_test.go create mode 100644 cspell.yaml create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/cache.go create mode 100644 internal/deps_dev.go create mode 100644 internal/go_list.go create mode 100644 internal/go_proxy.go create mode 100644 internal/module.go create mode 100644 output.go create mode 100644 package.json create mode 100755 scripts/check-formatting.sh create mode 100755 scripts/check-trailing-whitespaces.bash create mode 100755 scripts/ensure_installed.sh create mode 100644 scripts/format-cspell-config.js create mode 100755 scripts/makefile-help.awk create mode 100644 source.go create mode 160000 test/bats create mode 100755 test/inputs/generate_responses.sh create mode 100644 test/inputs/go.mod create mode 100644 test/inputs/go.sum create mode 100644 test/inputs/responses.json create mode 100644 test/outputs/all_details_for_all_dependencies create mode 100644 test/outputs/basic_usage create mode 100644 test/outputs/modules_cache create mode 100644 test/outputs/output.csv create mode 100644 test/outputs/output.json create mode 100644 test/outputs/show_indirect create mode 100644 test/outputs/show_releases create mode 100644 test/outputs/show_versions create mode 100644 test/outputs/skip_fresh create mode 100644 test/outputs/skip_fresh_show_indirect create mode 100644 test/test.bats create mode 160000 test/test_helper/bats-assert create mode 160000 test/test_helper/bats-support create mode 100644 test/test_server.go diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..c277ce3 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @nieomylnieja diff --git a/.github/renovate.json5 b/.github/renovate.json5 new file mode 100644 index 0000000..40cd625 --- /dev/null +++ b/.github/renovate.json5 @@ -0,0 +1,30 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": [ + "schedule:nonOfficeHours", // https://docs.renovatebot.com/presets-schedule/#schedulenonofficehours + ":enableVulnerabilityAlertsWithLabel(security)", // https://docs.renovatebot.com/presets-default/#enablevulnerabilityalertswithlabelarg0 + "group:recommended", // https://docs.renovatebot.com/presets-group/#grouprecommended + "workarounds:all", // https://docs.renovatebot.com/presets-workarounds/#workaroundsall + ], + "reviewersFromCodeOwners": true, + "dependencyDashboard": true, + "semanticCommits": "disabled", + "labels": ["dependencies", "renovate"], + "prHourlyLimit": 1, + "prConcurrentLimit": 5, + "rebaseWhen": "conflicted", + "rangeStrategy": "pin", + "branchPrefix": "renovate_", + // Manager-specific configs: + // This will run go mod tidy after each go.mod update. + "postUpdateOptions": ["gomodTidy"], + // Custom version extraction from Makefile. + "regexManagers": [ + { + "fileMatch": ["^Makefile$"], + "matchStrings": [ + ".*renovate datasource=(?.*?) depName=(?.*?)\\n.*?_VERSION\\s?:=\\s?(?.*)\\s" + ] + } + ], +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ddd954a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,43 @@ +name: CI checks +on: + push: + branches: + - main + pull_request: + branches: + - main +jobs: + check: + runs-on: ubuntu-latest + env: + GO111MODULE: on + steps: + - name: Check out code + uses: actions/checkout@v4 + - uses: actions/setup-go@v4 + with: + go-version-file: go.mod + check-latest: true + - name: Set up prerequisites - node and yarn + uses: actions/setup-node@v3 + - name: Set up yarn cache + id: yarn-cache + run: echo "::set-output name=dir::$(yarn cache dir)" + - uses: actions/cache@v3 + with: + path: ${{ steps.yarn-cache.outputs.dir }} + key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} + restore-keys: | + ${{ runner.os }}-yarn- + - name: Run spell and markdown checkers + run: make check/spell check/trailing check/markdown + - name: Check formatting + run: make check/format + - name: Run go vet + run: make check/vet + - name: Run golangci-lint + run: make check/lint + - name: Run Gosec Security Scanner + run: make check/gosec + - name: Run unit tests + run: make test diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..16587be --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,25 @@ +name: Release +on: + push: + tags: + - 'v*' +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Checkout Source + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Set up Go + uses: actions/setup-go@v4 + with: + go-version-file: go.mod + check-latest: true + - name: Release Binaries + uses: goreleaser/goreleaser-action@v5 + with: + version: latest + args: release --clean + env: + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} \ No newline at end of file diff --git a/.github/workflows/scan.yml b/.github/workflows/scan.yml new file mode 100644 index 0000000..95e337b --- /dev/null +++ b/.github/workflows/scan.yml @@ -0,0 +1,24 @@ +name: Scan vulnerabilities +on: + push: + branches: + - main + pull_request: + branches: + - main + schedule: + # Run at 8:00 AM every weekday. + - cron: '0 8 * * 1-5' +jobs: + scan: + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + - name: Setup Golang + uses: actions/setup-go@v4 + with: + go-version-file: go.mod + check-latest: true + - name: Run Golang Vulncheck + run: make check/vulns diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f71d83f --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# If you prefer the allow list template instead of the deny list, see community template: +# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore +# +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib +bin/ + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +vendor/ + +# Go workspace file +go.work + +# Node +node_modules/ +yarn.lock +yarn-error.log diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..000929d --- /dev/null +++ b/.gitmodules @@ -0,0 +1,9 @@ +[submodule "test/bats"] + path = test/bats + url = https://github.com/bats-core/bats-core.git +[submodule "test/test_helper/bats-assert"] + path = test/test_helper/bats-assert + url = https://github.com/bats-core/bats-assert.git +[submodule "test/test_helper/bats-support"] + path = test/test_helper/bats-support + url = https://github.com/bats-core/bats-assert.git diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..736de88 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,91 @@ +run: + timeout: 5m + modules-download-mode: readonly + skip-dirs: + - scripts + - test + skip-dirs-use-default: true + +issues: + # Enable all checks (which was as default disabled e.g. comments). + exclude-use-default: false + # Value 0 means show all. + max-issues-per-linter: 0 + max-same-issues: 0 + +linters-settings: + revive: + rules: + - name: package-comments + disabled: true + goimports: + # Put imports beginning with prefix after 3rd-party packages; + # it's a comma-separated list of prefixes. + local-prefixes: github.com/nieomylnieja/go-libyear + govet: + # False positives and reporting on error shadowing (which is intended). + # Quoting Robi Pike: + # The shadow code is marked experimental. + # It has too many false positives to be enabled by default, so this is not entirely unexpected, + # but don't expect a fix soon. The right way to detect shadowing without flow analysis is elusive. + # Few years later (comment from 2015) and the Shadow analyer is still experimental... + check-shadowing: false + lll: + line-length: 120 + gocritic: + enabled-tags: + - opinionated + exhaustive: + default-signifies-exhaustive: true + errcheck: + exclude-functions: + - Body.Close() + misspell: + locale: US + +linters: + disable-all: true + enable: + # All linters from list https://golangci-lint.run/usage/linters/ are speciefed here and explicit enable/disable. + - asasalint + - asciicheck + - bodyclose + - errcheck + - exhaustive + - exportloopref + - gocheckcompilerdirectives + - gochecknoinits + - gocritic + - godot + - gofmt + - goheader + - goimports + - goprintffuncname + - gosimple + - govet + - importas + - ireturn + - ineffassign + - lll + - makezero + - mirror + - misspell + - nakedret + - nilerr + - nilnil + - prealloc + - predeclared + - revive + - rowserrcheck + - sloglint + - staticcheck + - tenv + - testifylint + - thelper + - tparallel + - typecheck + - unconvert + - unparam + - unused + - wastedassign + - whitespace diff --git a/.gorelaser.yml b/.gorelaser.yml new file mode 100644 index 0000000..1dd7ce0 --- /dev/null +++ b/.gorelaser.yml @@ -0,0 +1,24 @@ +project_name: go-libyear + +release: + github: + owner: nieomylnieja + name: go-libyear + +builds: + - main: ./cmd/ + binary: go-libyear + goos: + - darwin + - linux + - windows + goarch: + - amd64 + - arm64 + ldflags: -X main.Version={{.Version}} -X main.GitTag={{.Tag}} -X main.BuildDate={{.Date}} + env: + - CGO_ENABLED=0 + +checksum: + name_template: {{ .ProjectName }}-{{ .Version }}-SHA256SUMS' + algorithm: sha256 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e72bfdd --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b60bfe5 --- /dev/null +++ b/Makefile @@ -0,0 +1,180 @@ +.DEFAULT_GOAL := help +MAKEFLAGS += --silent --no-print-directory + +PROJECT=go-libyear +LDFLAGS := -s -w +BIN_DIR := ./bin +MAIN_DIR := ./cmd +TEST_DIR := ./test +BATS_FLAGS = --pretty +ifeq (${BATS_DEBUG}, true) + BATS_FLAGS += --trace --verbose-run +endif +BATS_BIN = $(TEST_DIR)/bats/bin/bats + +# renovate datasource=github-releases depName=securego/gosec +GOSEC_VERSION := v2.18.2 +# renovate datasource=github-releases depName=golangci/golangci-lint +GOLANGCI_LINT_VERSION := v1.55.2 +# renovate datasource=go depName=golang.org/x/vuln/cmd/govulncheck +GOVULNCHECK_VERSION := v1.0.1 +# renovate datasource=go depName=golang.org/x/tools/cmd/goimports +GOIMPORTS_VERSION := v0.14.0 + +# Check if the program is present in $PATH and install otherwise. +# ${1} - oneOf{binary,yarn} +# ${2} - program name +define _ensure_installed + LOCAL_BIN_DIR=$(BIN_DIR) ./scripts/ensure_installed.sh "${1}" "${2}" +endef + +# Install Go binary using 'go install' with an output directory set via $GOBIN. +# ${1} - repository url +define _install_go_binary + GOBIN=$(realpath $(BIN_DIR)) go install "${1}" +endef + +# Print Makefile target step description for check. +# Only print 'check' steps this way, and not dependent steps, like 'install'. +# ${1} - step description +define _print_step + printf -- '------\n%s...\n' "${1}" +endef + +.PHONY: build +## Build the binary. +build: + CGO_ENABLED=0 go build -ldflags="$(LDFLAGS)" -o $(BIN_DIR)/$(PROJECT) $(MAIN_DIR) + +.PHONY: release +## Build and release the binaries. +release: + @goreleaser release --snapshot --clean + +.PHONY: test test/unit test/cli +## Run all tests. +test: test/unit test/cli + +## Run cli bats tests. +test/cli: test/cli/init + $(call _print_step,Running cli tests) + $(BATS_BIN) $(BATS_FLAGS) $(TEST_DIR)/*.bats + +## Initialize bats tests framework. +test/cli/init: + git submodule update --init --recursive test/ + +## Run all unit tests. +test/unit: + $(call _print_step,Running unit tests) + go test -race -cover ./... + +.PHONY: check check/vet check/lint check/gosec check/spell check/trailing check/markdown check/format check/vulns +## Run all checks. +check: check/vet check/lint check/gosec check/spell check/trailing check/markdown check/format check/vulns + +## Run 'go vet' on the whole project. +check/vet: + $(call _print_step,Running go vet) + go vet ./... + +## Run golangci-lint all-in-one linter with configuration defined inside .golangci.yml. +check/lint: + $(call _print_step,Running golangci-lint) + $(call _ensure_installed,binary,golangci-lint) + $(BIN_DIR)/golangci-lint run + +## Check for security problems using gosec, which inspects the Go code by scanning the AST. +check/gosec: + $(call _print_step,Running gosec) + $(call _ensure_installed,binary,gosec) + $(BIN_DIR)/gosec -exclude-dir=test -exclude-generated -quiet ./... + +## Check spelling, rules are defined in cspell.json. +check/spell: + $(call _print_step,Verifying spelling) + $(call _ensure_installed,yarn,cspell) + yarn --silent cspell --no-progress '**/**' + +## Check for trailing whitespaces in any of the projects' files. +check/trailing: + $(call _print_step,Looking for trailing whitespaces) + ./scripts/check-trailing-whitespaces.bash + +## Check markdown files for potential issues with markdownlint. +check/markdown: + $(call _print_step,Verifying Markdown files) + $(call _ensure_installed,yarn,markdownlint) + yarn --silent markdownlint '*.md' --disable MD010, MD034 # MD010 does not handle code blocks well. + +## Check for potential vulnerabilities across all Go dependencies. +check/vulns: + $(call _print_step,Running govulncheck) + $(call _ensure_installed,binary,govulncheck) + $(BIN_DIR)/govulncheck ./... + +## Verify if the files are formatted. +## You must first commit the changes, otherwise it won't detect the diffs. +check/format: + $(call _print_step,Checking if files are formatted) + ./scripts/check-formatting.sh + +.PHONY: generate +## Generate Golang code. +generate: + echo "Generating Go code..." + #$(call _ensure_installed,binary,go-enum) + go generate ./... + +.PHONY: format format/go format/cspell +## Format files. +format: format/go format/cspell + +## Format Go files. +format/go: + echo "Formatting Go files..." + $(call _ensure_installed,binary,goimports) + go fmt ./... + $(BIN_DIR)/goimports -local=$$(head -1 go.mod | awk '{print $$2}') -w . + +## Format cspell config file. +format/cspell: + echo "Formatting cspell.yaml configuration (words list)..." + $(call _ensure_installed,yarn,yaml) + yarn --silent format-cspell-config + +.PHONY: install install/yarn install/golangci-lint install/gosec install/govulncheck install/goimports +## Install all dev dependencies. +install: install/yarn install/golangci-lint install/gosec install/govulncheck install/goimports + +## Install JS dependencies with yarn. +install/yarn: + echo "Installing yarn dependencies..." + yarn --silent install + +## Install golangci-lint (https://golangci-lint.run). +install/golangci-lint: + echo "Installing golangci-lint..." + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh |\ + sh -s -- -b $(BIN_DIR) $(GOLANGCI_LINT_VERSION) + +## Install gosec (https://github.com/securego/gosec). +install/gosec: + echo "Installing gosec..." + curl -sfL https://raw.githubusercontent.com/securego/gosec/master/install.sh |\ + sh -s -- -b $(BIN_DIR) $(GOSEC_VERSION) + +## Install govulncheck (https://pkg.go.dev/golang.org/x/vuln/cmd/govulncheck). +install/govulncheck: + echo "Installing govulncheck..." + $(call _install_go_binary,golang.org/x/vuln/cmd/govulncheck@$(GOVULNCHECK_VERSION)) + +## Install goimports (https://pkg.go.dev/golang.org/x/tools/cmd/goimports). +install/goimports: + echo "Installing goimports..." + $(call _install_go_binary,golang.org/x/tools/cmd/goimports@$(GOIMPORTS_VERSION)) + +.PHONY: help +## Print this help message. +help: + ./scripts/makefile-help.awk $(MAKEFILE_LIST) diff --git a/README.md b/README.md new file mode 100644 index 0000000..8649080 --- /dev/null +++ b/README.md @@ -0,0 +1,181 @@ +# go-libyear + +Calculate Go module's libyear! + +## Calculated metrics + +### Libyear + +What exactly is _libyear_? +Quoting and paraphrasing [libyear.com](https://libyear.com/): +> Libyear is a simple measure of software **dependency freshness**. \ +> It is a single number telling you how **up-to-date** your dependencies +> are. \ +> Example: pkg/errors _v0.8.1_ (January 2019) is **1 libyear** behind _v0.9.0_ +> (June 2020). + +Libyear is the default metric calculated by the program. + +Example: + +| Current | Current release | Latest | Latest release | Libyear | +|---------|-----------------|---------|----------------|--| +| v1.45.1 | 2022-10-11 | v2.0.5 | 2022-10-16 | | +| v1.45.1 | | v1.47.5 | | (0,2,0) | +| v1.45.1 | | v1.47.5 | | (0,2,0) | + +### Number of releases + +Dependencies with short release cycles are penalized by this measurement, | +as the version sequence distance is relatively high compared to other +dependencies. + +Example: + +| Current | Latest | Delta | +|---------|---------|---------| +| v1.45.1 | v2.0.5 | (1,0,0) | +| v1.45.1 | v1.47.5 | (0,2,0) | + +### Version number delta + +Version delta is a tuple (x,y,z) where: + +- x is major version +- y is minor version +- z is patch version + +Only highest-order version number is taken into consideration. + +Example: + +| Current | Latest | Delta | +|---------|---------|---------| +| v1.45.1 | v2.0.5 | (1,0,0) | +| v1.45.1 | v1.47.5 | (0,2,0) | +| v1.45.1 | v.45.5 | (0,0,4) | + +## Install + +Use pre-built binaries from +the [latest release](https://github.com/nieomylnieja/go-libyear/releases/latest) +or install +with Go: + +```shell +go install github.com/nieomylnieja/go-libyear@latest +``` + +It can also be built directly from this repository: + +```shell +git clone https://github.com/nieomylnieja/go-libyear.git +cd go-libyear +make build +./bin/go-libyear ./go.mod +``` + +## Usage + +`go-libyear` can be used both as a CLI and Go library. +The CLI usage is also documented in [usage.txt](./cmd/usage.txt) +and accessed through `go-libyear --help`. + +Basic usage: + +```shell +$ go-libyear /path/to/go.mod +package version date latest latest_date libyear +github.com/nieomylnieja/go-libyear 2023-11-06 2.41 +github.com/pkg/errors v0.8.1 2019-01-03 v0.9.1 2020-01-14 1.03 +github.com/urfave/cli/v2 v2.20.0 2022-10-14 v2.25.7 2023-06-14 0.67 +golang.org/x/mod v0.12.0 2023-06-21 v0.14.0 2023-10-25 0.35 +golang.org/x/sync v0.3.0 2023-06-01 v0.5.0 2023-10-11 0.36 +``` + +### Results manipulation + +| Flag | Explanation | +|----------------|------------------------------------------------------------| +| `--releases` | Count number of releases between current and latest. | +| `--versions` | Calculate version number delta between current and latest. | +| `--indirect` | Include indirect dependencies in the results. | +| `--skip-fresh` | Skip up-to-date dependencies from the results. | + +### Module sources + + +| Source | Flag | Example | +|-------------|-----------|-----------------------------------------------------------------------| +| File path | _default_ | ~/my-project/go.mod | +| URL | `--url` | https://raw.githubusercontent.com/nieomylnieja/go-libyear/main/go.mod | +| Module path | `--pkg` | github.com/nieomylnieja/go-libyear@latest | + + +### Output formats + +| Format | Flag | +|--------|-----------| +| Table | _default_ | +| JSON | `--json` | +| CSV | `--csv` | + +### Caching + +`go-libyear` ships with a built-in caching mechanism. +It is disabled by default but can be enabled and adjusted with the following +flags: + +| Flag | Explanation | +|---------------------|-------------------------------------| +| `--cache` | Enable caching. | +| `--cache-file-path` | Use the specified file fro caching. | + +## Caveats + +### Accessing private repositories + +Currently the default mode of execution does not support GOPRIVATE environment +variable. +This means private modules' information won't be accessible to the program. To +access +private modules use `--go-list` flag. It will instruct the program to +utilize `go list` +command instead of GOPROXY API. + +### Using `--go-list` flag + +If `--go-list` flag is provided, `go-libyear` will used `go list` command to +fetch information about modules. +Specifically it runs `go list -m -mod=readonly`. +If the program is executed in a project containing a `go.mod` which `go.sum` +file is out of sync, +it will drop the following error: + +```text +updates to go.sum needed, disabled by -mod=readonly +``` + +Due to that it is advised to use stick with default modules information +provider. + +## Development + +CLI application is tested +with [bats framework](https://github.com/bats-core/bats-core). +The tests are defined in `test` folder. +Only core calculations are covered by unit tests, main paths are tested through +CLI tests. + +## Acknowledgements + +Inspired directly +by [SE Radio episode 587](https://www.se-radio.net/2023/10/se-radio-587-m-scott-ford-on-managing-dependency-freshness/). +Further reading through https://libyear.com/ and +mimicking https://github.com/jaredbeck/libyear-bundler capabilities. + +All the concepts and theory is based +on or directly quoted +from [Measuring Dependency Freshness in Software Systems][1]. + +[1]: (J. Cox, E. Bouwers, M. van Eekelen and J. Visser, Measuring Dependency Freshness in Software Systems. In Proceedings of the 37th International Conference on Software Engineering, May 2015) diff --git a/bin/.keep b/bin/.keep new file mode 100644 index 0000000..e69de29 diff --git a/builder.go b/builder.go new file mode 100644 index 0000000..4a41e02 --- /dev/null +++ b/builder.go @@ -0,0 +1,71 @@ +package libyear + +import "github.com/nieomylnieja/go-libyear/internal" + +func NewCommandBuilder(source Source, output Output) CommandBuilder { + return CommandBuilder{ + source: source, + output: output, + } +} + +type CommandBuilder struct { + source Source + output Output + repo ModulesRepo + fallback VersionsGetter + withCache bool + cacheFilePath string + opts Option +} + +func (b CommandBuilder) WithCache(cacheFilePath string) CommandBuilder { + b.withCache = true + b.cacheFilePath = cacheFilePath + return b +} + +func (b CommandBuilder) WithModulesRepo(repo ModulesRepo) CommandBuilder { + b.repo = repo + return b +} + +func (b CommandBuilder) WithFallbackVersionsGetter(getter VersionsGetter) CommandBuilder { + b.fallback = getter + return b +} + +func (b CommandBuilder) WithOptions(opts ...Option) CommandBuilder { + for _, opt := range opts { + b.opts |= opt + } + return b +} + +func (b CommandBuilder) Build() (*Command, error) { + if b.repo == nil { + var err error + if b.opts&OptionUseGoList != 0 { + b.repo, err = internal.NewGoListExecutor(b.withCache, b.cacheFilePath) + } else { + b.repo, err = internal.NewGoProxyClient(b.withCache, b.cacheFilePath) + } + if err != nil { + return nil, err + } + } + if b.fallback == nil { + b.fallback = internal.NewDepsDevClient() + } + // Share initialized ModulesRepo with sources. + if v, ok := b.source.(interface{ SetModulesRepo(repo ModulesRepo) }); ok { + v.SetModulesRepo(b.repo) + } + return &Command{ + source: b.source, + output: b.output, + repo: b.repo, + fallbackVersions: b.fallback, + opts: b.opts, + }, nil +} diff --git a/cmd/flags.go b/cmd/flags.go new file mode 100644 index 0000000..a2f85bf --- /dev/null +++ b/cmd/flags.go @@ -0,0 +1,108 @@ +package main + +import ( + "fmt" + "time" + + "github.com/pkg/errors" + "github.com/urfave/cli/v2" + + golibyear "github.com/nieomylnieja/go-libyear" +) + +const ( + categorySource = "Source:" + categoryOutput = "Output:" + categoryCache = "Cache:" +) + +var flagToOption = map[string]golibyear.Option{ + flagIndirect.Name: golibyear.OptionIncludeIndirect, + flagSkipFresh.Name: golibyear.OptionSkipFresh, + flagReleases.Name: golibyear.OptionShowReleases, + flagVersions.Name: golibyear.OptionShowVersions, + flagUseGoList.Name: golibyear.OptionUseGoList, +} + +var ( + flagURL = &cli.BoolFlag{ + Name: "url", + Aliases: []string{"u"}, + Usage: "Fetch go.mod from URL", + Category: categorySource, + } + flagPkg = &cli.BoolFlag{ + Name: "pkg", + Aliases: []string{"p"}, + Usage: "Fetch go.mod from pkg index", + Category: categorySource, + } + flagJSON = &cli.BoolFlag{ + Name: "json", + Usage: "Output using JSON format", + Category: categoryOutput, + } + flagCSV = &cli.BoolFlag{ + Name: "csv", + Usage: "Output using CSV format", + Category: categoryOutput, + } + flagCache = &cli.BoolFlag{ + Name: "cache", + Usage: "Use cache", + Category: categoryCache, + } + flagCacheFilePath = &cli.PathFlag{ + Name: "cache-file-path", + Usage: "Use custom cache file path", + DefaultText: "$XDG_CACHE_HOME/go-libyear/modules or $HOME/.cache/go-libyear/modules", + Category: categoryCache, + Action: func(c *cli.Context, path cli.Path) error { + if !c.IsSet("cache") { + return errors.Errorf("--cache-file-path flag can only be used in conjunction with --cache") + } + return nil + }, + } + flagTimeout = &cli.DurationFlag{ + Name: "timeout", + Aliases: []string{"t"}, + Value: 1 * time.Minute, + Usage: "Set timeout for the command", + } + flagUseGoList = &cli.BoolFlag{ + Name: "go-list", + Usage: "Use 'go list -m' instead of GOPROXY API", + } + flagIndirect = &cli.BoolFlag{ + Name: "indirect", + Aliases: []string{"i"}, + Usage: "Include indirect dependencies", + Category: categoryOutput, + } + flagSkipFresh = &cli.BoolFlag{ + Name: "skip-fresh", + Usage: "Skip up-to-date dependencies", + Category: categoryOutput, + } + flagReleases = &cli.BoolFlag{ + Name: "releases", + Usage: "Display the number of releases between current and newest versions", + Category: categoryOutput, + } + flagVersions = &cli.BoolFlag{ + Name: "versions", + Usage: "Display the number of major, minor, and patch versions between current and newest versions", + Category: categoryOutput, + } + flagVersion = &cli.BoolFlag{ + Name: "version", + Aliases: []string{"v"}, + Usage: "Show the program version", + Action: func(context *cli.Context, b bool) error { + fmt.Printf("Version: %s\nGitTag: %s\nBuildDate: %s\n", + BuildVersion, BuildGitTag, BuildDate) + return nil + }, + } +) diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..158982e --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,171 @@ +package main + +import ( + "context" + _ "embed" + "fmt" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + golibyear "github.com/nieomylnieja/go-libyear" + "github.com/nieomylnieja/go-libyear/internal" + + "github.com/pkg/errors" + "github.com/urfave/cli/v2" +) + +// Set by build ldflags. +var ( + BuildVersion string + BuildGitTag string + BuildDate string +) + +//go:embed usage.txt +var usageText string + +func main() { + app := &cli.App{ + Usage: "Calculate Go module's libyear!", + UsageText: usageText, + Action: run, + Name: internal.ProgramName, + Flags: []cli.Flag{ + flagURL, + flagPkg, + flagCSV, + flagJSON, + flagCache, + flagCacheFilePath, + flagTimeout, + flagUseGoList, + flagIndirect, + flagSkipFresh, + flagReleases, + flagVersions, + flagVersion, + }, + Suggest: true, + } + if err := app.Run(os.Args); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + os.Exit(1) + } +} + +func run(cliCtx *cli.Context) error { + if cliCtx.IsSet(flagVersion.Name) { + return nil + } + + ctx, watch := setupContextHandling(cliCtx) + go watch() + + stdinUsed := isStdinUsed() + if err := validateArgs(cliCtx, stdinUsed); err != nil { + return err + } + + var source golibyear.Source + sourceArg := cliCtx.Args().Get(0) + switch { + case cliCtx.IsSet(flagPkg.Name): + source = &golibyear.PkgSource{Pkg: sourceArg} + case cliCtx.IsSet(flagURL.Name): + source = golibyear.URLSource{RawURL: sourceArg, HTTP: http.Client{Timeout: 10 * time.Second}} + case stdinUsed: + source = golibyear.StdinSource{} + default: + source = golibyear.FileSource{Path: sourceArg} + } + + var output golibyear.Output + switch { + case cliCtx.IsSet(flagJSON.Name): + output = golibyear.JSONOutput{} + case cliCtx.IsSet(flagCSV.Name): + output = golibyear.CSVOutput{} + default: + output = golibyear.TableOutput{} + } + + builder := golibyear.NewCommandBuilder(source, output) + if cliCtx.IsSet(flagCache.Name) { + builder = builder.WithCache(flagCacheFilePath.Get(cliCtx)) + } + for flag, option := range flagToOption { + if cliCtx.IsSet(flag) { + builder = builder.WithOptions(option) + } + } + + cmd, err := builder.Build() + if err != nil { + return err + } + return cmd.Run(ctx) +} + +func setupContextHandling(cliCtx *cli.Context) (ctx context.Context, handler func()) { + ctx = cliCtx.Context + ctx, cancel := context.WithTimeout(ctx, flagTimeout.Get(cliCtx)) + sigCh := make(chan os.Signal, 2) + signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) + return ctx, func() { + select { + case sig := <-sigCh: + cancel() + fmt.Printf("\r%s signal detected, shutting down...\n", sig) + os.Exit(0) + case <-ctx.Done(): + fmt.Printf("\r%s, shutting down...\n", ctx.Err()) + os.Exit(1) + } + } +} + +func validateArgs(cliCtx *cli.Context, stdinUsed bool) error { + if cliCtx.NArg() != 1 && !stdinUsed { + return errors.New("invalid number of arguments provided, expected a single argument, path to go.mod") + } + if stdinUsed && (cliCtx.NArg() != 0 || cliCtx.IsSet(flagURL.Name) || cliCtx.IsSet(flagPkg.Name)) { + return errors.Errorf( + "when reading go.mod from stdin no arguments or output related flags should be provided") + } + + for _, flags := range [][]string{ + {flagUseGoList.Name, flagPkg.Name}, + {flagCSV.Name, flagJSON.Name}, + {flagURL.Name, flagPkg.Name}, + } { + if err := validateFlagsMutualExclusion(cliCtx, flags); err != nil { + return err + } + } + return nil +} + +func isStdinUsed() bool { + stat, err := os.Stdin.Stat() + if err != nil { + return false + } + return stat.Mode()&os.ModeCharDevice == 0 +} + +func validateFlagsMutualExclusion(cliCtx *cli.Context, flags []string) error { + var flagSet string + for _, flag := range flags { + if !cliCtx.IsSet(flag) { + continue + } + if flagSet != "" { + return errors.Errorf("use either --%s or --%s flag, but not both", flagSet, flag) + } + flagSet = flag + } + return nil +} diff --git a/cmd/usage.txt b/cmd/usage.txt new file mode 100644 index 0000000..cc75925 --- /dev/null +++ b/cmd/usage.txt @@ -0,0 +1,40 @@ +go-libyear [flags] + +Calculate Go module's libyear! + +There are multiple ways to parse selected go.mod file. +Reading go.mod from the following sources is supported: + - file [default]: file path to a go.mod file + example: ./go.mod, /home/user/project/go.mod + - url: URL from which to fetch the file; the request is a simple GET + example: https://raw.githubusercontent.com/nieomylnieja/go-libyear/main/go.mod + - pkg: Go pkg name; if no version is provided, @latest will be appended to the name + example: github.com/nieomylnieja/go-libyear, github.com/nieomylnieja/go-libyear@v1.2.3 +In addition to these options the program will also detect stdin: + cat /home/me/project/go.mod | go-libyear + +The following details are computed: + - Package name + - Current version + - Date of the current version release + - Latest version + - Date of the latest version release + - Calculated libyear + - Releases count between current and latest (optional) + - Version number delta (optional) +The following output formats are supported: + - table [default] + - CSV + - JSON +The main module entry contains the sum of all dependencies' libyears. + +Under the hood, wherever possible GOPROXY API is queried to fetch modules' information. +The program respects GOPROXY environment variable. +This behavior can be changed to use `go list` instead with --go-list flag. + +The program ships with a builtin file-based cache. It is disabled by default, but can +be enabled with --cache flag. It will attempt to cache the modules information in +($XDG_CACHE_HOME|$HOME/.cache)/go-libyear directory. +Custom cache file location can be specified with --cache-file-path flag. + +More details on libyear: https://libyear.com/ \ No newline at end of file diff --git a/command.go b/command.go new file mode 100644 index 0000000..fb78ff8 --- /dev/null +++ b/command.go @@ -0,0 +1,215 @@ +package libyear + +import ( + "context" + "log" + "os" + "slices" + "sort" + "strconv" + "time" + + "github.com/nieomylnieja/go-libyear/internal" + + "github.com/Masterminds/semver" + "golang.org/x/sync/errgroup" +) + +type Option int + +const ( + OptionShowReleases Option = 1 << iota // 1 + OptionShowVersions // 2 + OptionSkipFresh // 4 + OptionIncludeIndirect // 8 + OptionUseGoList +) + +type ModulesRepo interface { + VersionsGetter + GetModFile(path string, version *semver.Version) ([]byte, error) + GetInfo(path string, version *semver.Version) (*internal.Module, error) + GetLatestInfo(path string) (*internal.Module, error) +} + +type VersionsGetter interface { + GetVersions(path string) ([]*semver.Version, error) +} + +type Command struct { + source Source + output Output + repo ModulesRepo + fallbackVersions VersionsGetter + opts Option +} + +func (c Command) Run(ctx context.Context) error { + data, err := c.source.Read() + if err != nil { + return err + } + + mainModule, modules, err := internal.ReadGoMod(data) + if err != nil { + return err + } + mainModule.Time = time.Now() + if !c.optionIsSet(OptionIncludeIndirect) { + // Filter out indirect. + modules = slices.DeleteFunc(modules, func(module *internal.Module) bool { return module.IsIndirect }) + } + + group, _ := c.newErrGroup(ctx) + for _, module := range modules { + module := module + group.Go(func() error { return c.runForModule(module) }) + } + if err = group.Wait(); err != nil { + return err + } + // Remove skipped modules. + if c.optionIsSet(OptionSkipFresh) { + modules = slices.DeleteFunc(modules, func(module *internal.Module) bool { return module.IsFresh }) + } + + // Aggregate results for main module. + for _, module := range modules { + mainModule.Libyear += module.Libyear + mainModule.ReleasesDiff += module.ReleasesDiff + mainModule.VersionsDiff = mainModule.VersionsDiff.Add(module.VersionsDiff) + } + + // Prepare and send summary. + return c.output.Send(Summary{ + Modules: modules, + Main: mainModule, + releases: c.optionIsSet(OptionShowReleases), + versions: c.optionIsSet(OptionShowVersions), + }) +} + +const secondsInYear = float64(365 * 24 * 60 * 60) + +func (c Command) runForModule(module *internal.Module) error { + // We skip this module, unless we get to the end and manage to calculate libyear. + module.IsFresh = true + // Since we're parsing the go.mod file directly, we might need to fetch the Module.Time. + if module.Time.IsZero() { + fetchedModule, err := c.repo.GetInfo(module.Path, module.Version) + if err != nil { + return err + } + module.Time = fetchedModule.Time + } + // Fetch all versions. + versions, err := c.repo.GetVersions(module.Path) + if err != nil { + return err + } + if len(versions) == 0 { + if module.Version.Prerelease() == "" { + log.Printf("WARN: module %s does not have any versions", module.Path) + return nil + } + // Try fetching the versions from deps.dev. + // Go list does not list prerelease versions, which is fine, + // unless we're dealing with with a prerelease version ourselves. + versions, err = c.fallbackVersions.GetVersions(module.Path) + if err != nil { + return err + } + // Check again. + if len(versions) == 0 { + log.Printf("WARN: module %s does not have any versions", module.Path) + return nil + } + } + sort.Sort(semver.Collection(versions)) + + latestVersion := versions[len(versions)-1] + // It returns -1 (smaller), 0 (larger), or 1 (greater) when compared. + if module.Version.Compare(latestVersion) != -1 { + module.Latest = module + return nil + } + // Fetch latest. + latest, err := c.repo.GetInfo(module.Path, latestVersion) + if err != nil { + return err + } + module.Latest = latest + + // The following calculations are based on https://ericbouwers.github.io/papers/icse15.pdf. + module.Libyear = calculateLibyear(module, latest) + if c.optionIsSet(OptionShowReleases) { + module.ReleasesDiff = calculateReleases(module, versions) + } + if c.optionIsSet(OptionShowVersions) { + module.VersionsDiff = calculateVersions(module, latest) + } + + module.IsFresh = false + return nil +} + +func calculateLibyear(module, latest *internal.Module) float64 { + diff := latest.Time.Sub(module.Time) + return diff.Seconds() / secondsInYear +} + +func calculateReleases(module *internal.Module, versions []*semver.Version) int { + currentIndex := slices.IndexFunc(versions, func(v *semver.Version) bool { return module.Version.Equal(v) }) + latestIndex := len(versions) - 1 + // Example: + // v: v1 | v2 | v3 | v4 + // i: 0 1 2 3 > len == 4 + // ^ ^ + // current (i:1) latest (i:3) + return latestIndex - currentIndex +} + +func calculateVersions(module, latest *internal.Module) internal.VersionsDiff { + // This takes a form of 3 element array. + // The delta is defined as the absolute difference between the + // highest-order version number which has changed compared to + // the previous version number tuple. + // Example: + // v1: v2.3.4 + // v2: v3.6.4 + // diff: [(3-2), 0, 0] = [1, 0, 0] + switch { + case latest.Version.Major() != module.Version.Major(): + return internal.VersionsDiff{ + latest.Version.Major() - module.Version.Major(), + 0, + 0, + } + case latest.Version.Minor() != module.Version.Minor(): + return internal.VersionsDiff{ + 0, + latest.Version.Minor() - module.Version.Minor(), + 0, + } + default: + return internal.VersionsDiff{ + 0, + 0, + latest.Version.Patch() - module.Version.Patch(), + } + } +} + +func (c Command) newErrGroup(ctx context.Context) (*errgroup.Group, context.Context) { + group, ctx := errgroup.WithContext(ctx) + maxProcs, _ := strconv.Atoi(os.Getenv("GOMAXPROCS")) + if maxProcs == 0 { + maxProcs = 4 + } + group.SetLimit(maxProcs) + return group, ctx +} + +func (c Command) optionIsSet(option Option) bool { + return c.opts&option != 0 +} diff --git a/command_test.go b/command_test.go new file mode 100644 index 0000000..243443c --- /dev/null +++ b/command_test.go @@ -0,0 +1,185 @@ +package libyear + +import ( + "math" + "strconv" + "testing" + "time" + + "github.com/Masterminds/semver" + "github.com/stretchr/testify/assert" + + "github.com/nieomylnieja/go-libyear/internal" +) + +func TestCommand_calculateLibyear(t *testing.T) { + mustParseTime := func(date string) time.Time { + t.Helper() + parsed, _ := time.Parse(time.DateOnly, date) + return parsed + } + + tests := []struct { + CurrentDate string + LatestDate string + Expected float64 + }{ + { + CurrentDate: "2021-05-12", + LatestDate: "2022-01-01", + Expected: 0.64, + }, + { + CurrentDate: "2021-01-01", + LatestDate: "2022-01-01", + Expected: 1.0, + }, + { + CurrentDate: "2021-02-28", + LatestDate: "2023-09-15", + Expected: 2.55, + }, + { + CurrentDate: "2022-01-01", + LatestDate: "2022-01-01", + Expected: 0.0, + }, + { + CurrentDate: "2021-05-12", + LatestDate: "2021-05-14", + Expected: 0.01, + }, + } + for i, test := range tests { + t.Run(strconv.Itoa(i), func(t *testing.T) { + actual := calculateLibyear( + &internal.Module{Time: mustParseTime(test.CurrentDate)}, + &internal.Module{Time: mustParseTime(test.LatestDate)}) + if test.Expected == 0 { + assert.Zero(t, actual) + } else { + assert.InEpsilon(t, test.Expected, math.Round(actual*100)/100, 0.01) + } + }) + } +} + +func TestCommand_calculateReleases(t *testing.T) { + tests := []struct { + CurrentVersion string + Versions []string + Expected int + }{ + { + CurrentVersion: "v0.9.0", + Versions: []string{ + "v0.9.0", + "v0.9.1", + "v0.9.2", + "v0.10.0", + "v1.0.0", + }, + Expected: 4, + }, + { + CurrentVersion: "v0.10.0", + Versions: []string{ + "v0.9.1", + "v0.9.2", + "v0.10.0", + "v1.0.0", + }, + Expected: 1, + }, + { + CurrentVersion: "v1.0.0", + Versions: []string{ + "v0.9.2", + "v0.10.0", + "v1.0.0", + }, + Expected: 0, + }, + { + CurrentVersion: "v1.0.0", + Versions: []string{ + "v1.0.0", + }, + Expected: 0, + }, + } + for i, test := range tests { + t.Run(strconv.Itoa(i), func(t *testing.T) { + versions := make([]*semver.Version, len(test.Versions)) + for i, v := range test.Versions { + versions[i] = semver.MustParse(v) + } + actual := calculateReleases( + &internal.Module{Version: semver.MustParse(test.CurrentVersion)}, + versions) + assert.Equal(t, test.Expected, actual) + }) + } +} + +func TestCommand_calculateVersions(t *testing.T) { + tests := []struct { + CurrentVersion string + LatestVersion string + Expected internal.VersionsDiff + }{ + { + CurrentVersion: "v0.0.0", + LatestVersion: "v0.0.0", + Expected: internal.VersionsDiff{0, 0, 0}, + }, + { + CurrentVersion: "v0.9.0", + LatestVersion: "v0.9.0", + Expected: internal.VersionsDiff{0, 0, 0}, + }, + { + CurrentVersion: "v0.0.1", + LatestVersion: "v0.0.1", + Expected: internal.VersionsDiff{0, 0, 0}, + }, + { + CurrentVersion: "v1.0.0", + LatestVersion: "v1.0.0", + Expected: internal.VersionsDiff{0, 0, 0}, + }, + { + CurrentVersion: "v1.9.0", + LatestVersion: "v2.10.2", + Expected: internal.VersionsDiff{1, 0, 0}, + }, + { + CurrentVersion: "v1.9.0", + LatestVersion: "v3.8.0", + Expected: internal.VersionsDiff{2, 0, 0}, + }, + { + CurrentVersion: "v1.9.0", + LatestVersion: "v1.12.0", + Expected: internal.VersionsDiff{0, 3, 0}, + }, + { + CurrentVersion: "v1.9.0", + LatestVersion: "v1.12.3", + Expected: internal.VersionsDiff{0, 3, 0}, + }, + { + CurrentVersion: "v1.9.0", + LatestVersion: "v1.9.12", + Expected: internal.VersionsDiff{0, 0, 12}, + }, + } + for i, test := range tests { + t.Run(strconv.Itoa(i), func(t *testing.T) { + actual := calculateVersions( + &internal.Module{Version: semver.MustParse(test.CurrentVersion)}, + &internal.Module{Version: semver.MustParse(test.LatestVersion)}) + assert.Equal(t, test.Expected, actual) + }) + } +} diff --git a/cspell.yaml b/cspell.yaml new file mode 100644 index 0000000..3b05b37 --- /dev/null +++ b/cspell.yaml @@ -0,0 +1,39 @@ +allowCompoundWords: true +language: en_US +dictionaries: + - misc + - softwareTerms + - go + - bash + - typescript + - node + - npm +ignoreRegExpList: + - /\|\s+[T|G]{2,}\s+\|/g + - /https?:\/\/.*/g + - /github.*/g + - /nolint.*/g + - /nosec.*/g +ignorePaths: + - cspell.json + - .golangci.yml + - "**/*.lock" + - "**/go.mod" + - "**/go.sum" + - "**/node_modules/**" + - CODEOWNERS + - bin/** + - test/** +words: + - endef + - gobin + - goimports + - golangci + - golibyear + - gosec + - govulncheck + - ifeq + - ldflags + - procs + - vuln + - vulns diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..aa9831d --- /dev/null +++ b/go.mod @@ -0,0 +1,21 @@ +module github.com/nieomylnieja/go-libyear + +go 1.21 + +require ( + github.com/Masterminds/semver v1.5.0 + github.com/pkg/errors v0.9.1 + github.com/stretchr/testify v1.8.4 + github.com/urfave/cli/v2 v2.25.7 + golang.org/x/mod v0.14.0 + golang.org/x/sync v0.5.0 +) + +require ( + github.com/cpuguy83/go-md2man/v2 v2.0.3 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..eb24fe1 --- /dev/null +++ b/go.sum @@ -0,0 +1,26 @@ +github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= +github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= +github.com/cpuguy83/go-md2man/v2 v2.0.3 h1:qMCsGGgs+MAzDFyp9LpAe1Lqy/fY/qCovCm0qnXZOBM= +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/urfave/cli/v2 v2.25.7 h1:VAzn5oq403l5pHjc4OhD54+XGO9cdKVL/7lDjF+iKUs= +github.com/urfave/cli/v2 v2.25.7/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ= +github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU= +github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= +golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= +golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE= +golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/cache.go b/internal/cache.go new file mode 100644 index 0000000..caed1f6 --- /dev/null +++ b/internal/cache.go @@ -0,0 +1,170 @@ +package internal + +import ( + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "sync" + "time" + + "github.com/Masterminds/semver" +) + +type modulesCache interface { + Load(path string, version *semver.Version) (*Module, bool) + Save(m *Module) error +} + +type cachePersistenceLayer interface { + Save(module persistedModule) error + Load() ([]persistedModule, error) +} + +func NewCache(filePath string) (*Cache, error) { + persistence, err := newFilePersistence(filePath) + if err != nil { + return nil, err + } + cache := &Cache{ + Modules: make(map[string]*Module), + rwm: sync.RWMutex{}, + persistence: persistence, + } + return cache, cache.loadFromPersistence() +} + +type Cache struct { + Modules map[string]*Module + rwm sync.RWMutex + persistence cachePersistenceLayer +} + +func (c *Cache) Load(path string, version *semver.Version) (module *Module, loaded bool) { + c.rwm.RLock() + defer c.rwm.RUnlock() + module, loaded = c.Modules[c.moduleHash(path, version)] + return +} + +func (c *Cache) Save(m *Module) error { + if c.Has(m) { + return nil + } + c.rwm.Lock() + defer c.rwm.Unlock() + // Second check if we were racing with another goroutine. + // We can't use read locks now (deadlock). + _, has := c.Modules[c.moduleHash(m.Path, m.Version)] + if has { + return nil + } + c.Modules[c.moduleHash(m.Path, m.Version)] = m + if c.persistence == nil { + return nil + } + return c.persistence.Save(persistedModule{ + Path: m.Path, + Version: m.Version, + Time: m.Time, + }) +} + +func (c *Cache) Has(m *Module) bool { + c.rwm.RLock() + defer c.rwm.RUnlock() + _, has := c.Modules[c.moduleHash(m.Path, m.Version)] + return has +} + +type persistedModule struct { + Path string `json:"path"` + Version *semver.Version `json:"version"` + Time time.Time `json:"time"` +} + +func (c *Cache) loadFromPersistence() error { + if c.persistence == nil { + return nil + } + c.rwm.Lock() + defer c.rwm.Unlock() + modules, err := c.persistence.Load() + if err != nil { + return err + } + for _, m := range modules { + hash := c.moduleHash(m.Path, m.Version) + if _, ok := c.Modules[hash]; ok { + fmt.Fprintf(os.Stderr, "WARN: duplicate module entry detected: %v\n", m) + continue + } + c.Modules[hash] = &Module{ + Path: m.Path, + Version: m.Version, + Time: m.Time, + } + } + return nil +} + +func (c *Cache) moduleHash(path string, version *semver.Version) string { + return path + "=" + version.String() +} + +func newFilePersistence(filePath string) (*filePersistence, error) { + if filePath == "" { + var err error + if filePath, err = getDefaultCacheFilePath(); err != nil { + return nil, err + } + } + // The function does an os.Stat under the hood anyway, so there's no gain in pre-checking this step. + if err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { + return nil, err + } + // #nosec G304 + f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0o600) + if err != nil { + return nil, err + } + return &filePersistence{file: f}, nil +} + +type filePersistence struct { + file *os.File +} + +func (f filePersistence) Save(module persistedModule) error { + return json.NewEncoder(f.file).Encode(module) +} + +func (f filePersistence) Load() ([]persistedModule, error) { + dec := json.NewDecoder(f.file) + modules := make([]persistedModule, 0) + for { + var m persistedModule + if err := dec.Decode(&m); err != nil { + if err == io.EOF { + break + } + return nil, err + } + modules = append(modules, m) + } + return modules, nil +} + +func getDefaultCacheFilePath() (string, error) { + const defaultFile = "modules" + filePath, envSet := os.LookupEnv("XDG_CACHE_HOME") + if envSet { + return filepath.Join(filePath, ProgramName, defaultFile), nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", err + } + return filepath.Join(home, ".config", ProgramName, defaultFile), nil +} diff --git a/internal/deps_dev.go b/internal/deps_dev.go new file mode 100644 index 0000000..2b955d2 --- /dev/null +++ b/internal/deps_dev.go @@ -0,0 +1,57 @@ +package internal + +import ( + "encoding/json" + "io" + "net/http" + "net/url" + "time" + + "github.com/Masterminds/semver" + "github.com/pkg/errors" +) + +func NewDepsDevClient() *DepsDevClient { + return &DepsDevClient{ + http: &http.Client{Timeout: 10 * time.Second}, + apiURL: url.URL{Scheme: "https", Host: "api.deps.dev"}, + } +} + +type DepsDevClient struct { + http *http.Client + apiURL url.URL +} + +func (c DepsDevClient) GetVersions(path string) ([]*semver.Version, error) { + path = url.PathEscape(path) + resp, err := c.http.Get(c.apiURL.JoinPath("v3alpha/systems/go/packages", path).String()) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + data, _ := io.ReadAll(resp.Body) + return nil, errors.Errorf( + "unexpected response status code: %d, body: %s", + resp.StatusCode, string(data)) + } + var data struct { + Versions []struct { + VersionKey struct { + Version *semver.Version `json:"version"` + } `json:"versionKey"` + } `json:"versions"` + } + if err = json.NewDecoder(resp.Body).Decode(&data); err != nil { + return nil, err + } + versions := make([]*semver.Version, 0, len(data.Versions)) + for _, v := range data.Versions { + if v.VersionKey.Version == nil { + continue + } + versions = append(versions, v.VersionKey.Version) + } + return versions, nil +} diff --git a/internal/go_list.go b/internal/go_list.go new file mode 100644 index 0000000..81be388 --- /dev/null +++ b/internal/go_list.go @@ -0,0 +1,104 @@ +package internal + +import ( + "bytes" + "encoding/json" + "os/exec" + + "github.com/Masterminds/semver" + + "github.com/pkg/errors" +) + +func NewGoListExecutor(useCache bool, cacheFilePath string) (*GoListExecutor, error) { + var cache modulesCache + if useCache { + var err error + cache, err = NewCache(cacheFilePath) + if err != nil { + return nil, err + } + } + return &GoListExecutor{cache: cache}, nil +} + +type GoListExecutor struct { + cache modulesCache +} + +func (e *GoListExecutor) GetVersions(path string) ([]*semver.Version, error) { + out, err := e.exec("-versions", path) + if err != nil { + return nil, err + } + var versions struct { + Path string `json:"Path"` + Versions []*semver.Version `json:"Versions"` + } + if err = json.NewDecoder(out).Decode(&versions); err != nil { + return nil, err + } + return versions.Versions, nil +} + +func (e *GoListExecutor) GetInfo(path string, version *semver.Version) (*Module, error) { + return e.getInfo(path, version, false) +} + +func (e *GoListExecutor) GetLatestInfo(path string) (*Module, error) { + return e.getInfo(path, nil, true) +} + +func (e *GoListExecutor) getInfo(path string, version *semver.Version, latest bool) (*Module, error) { + var versionStr string + if latest { + versionStr = "latest" + } else { + versionStr = version.String() + } + // Try loading from cache. + if e.cache != nil { + m, loaded := e.cache.Load(path, version) + if loaded { + return m, nil + } + } + // Fetch module details. + out, err := e.exec(path + "@v" + versionStr) + if err != nil { + return nil, err + } + var m Module + if err = json.NewDecoder(out).Decode(&m); err != nil { + return nil, err + } + // Save to cache. + if e.cache != nil { + if err = e.cache.Save(&m); err != nil { + return nil, err + } + } + return &m, nil +} + +func (e *GoListExecutor) GetModFile(_ string, _ *semver.Version) ([]byte, error) { + return nil, errors.New("retrieving go.mod file using GoListExecutor is not supported") +} + +func (e *GoListExecutor) exec(args ...string) (*bytes.Buffer, error) { + // #nosec G204 + cmd := exec.Command("go", append([]string{"list", "-json", "-m", "-mod=readonly"}, args...)...) + if cmd.Stdout != nil { + return nil, errors.New("exec: Stdout already set") + } + if cmd.Stderr != nil { + return nil, errors.New("exec: Stderr already set") + } + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + return nil, errors.Errorf("Failed to execute '%s' command: %s", cmd, stderr.String()) + } + return &stdout, nil +} diff --git a/internal/go_proxy.go b/internal/go_proxy.go new file mode 100644 index 0000000..abba351 --- /dev/null +++ b/internal/go_proxy.go @@ -0,0 +1,146 @@ +package internal + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "regexp" + "strings" + "time" + + "github.com/Masterminds/semver" + "github.com/pkg/errors" +) + +func NewGoProxyClient(useCache bool, cacheFilePath string) (*GoProxyClient, error) { + var cache modulesCache + if useCache { + var err error + cache, err = NewCache(cacheFilePath) + if err != nil { + return nil, err + } + } + apiURL := url.URL{Scheme: "https", Host: "proxy.golang.org"} + if proxyURL, isSet := os.LookupEnv("GOPROXY"); isSet { + u, err := url.Parse(proxyURL) + if err != nil { + return nil, errors.Wrap(err, "failed to parse $GOPROXY url") + } + apiURL = *u + } + return &GoProxyClient{ + http: &http.Client{Timeout: 10 * time.Second}, + apiURL: apiURL, + cache: cache, + }, nil +} + +// GoProxyClient is used to interact with Golang proxy server. +// Details on GOPROXY protocol can be found here: https://go.dev/ref/mod#goproxy-protocol. +type GoProxyClient struct { + http *http.Client + apiURL url.URL + cache modulesCache +} + +const ( + getModFileFmt = "%s/@v/v%s.mod" + getLatestInfoFmt = "%s/@latest" + getVersionInfoFmt = "%s/@v/v%s.info" + getVersionsFmt = "%s/@v/list" +) + +func (c *GoProxyClient) GetInfo(path string, version *semver.Version) (*Module, error) { + return c.getInfo(path, version, false) +} + +func (c *GoProxyClient) GetLatestInfo(path string) (*Module, error) { + return c.getInfo(path, nil, true) +} + +func (c *GoProxyClient) getInfo(path string, version *semver.Version, latest bool) (*Module, error) { + // Try loading from cache. + if c.cache != nil { + m, loaded := c.cache.Load(path, version) + if loaded { + return m, nil + } + } + path = escapePath(path) + var urlPath string + if latest { + urlPath = fmt.Sprintf(getLatestInfoFmt, path) + } else { + urlPath = fmt.Sprintf(getVersionInfoFmt, path, version) + } + data, err := c.query(urlPath) + if err != nil { + return nil, err + } + var m Module + if err = json.Unmarshal(data, &m); err != nil { + return nil, err + } + // Save to cache. + if c.cache != nil { + if err = c.cache.Save(&m); err != nil { + return nil, err + } + } + return &m, nil +} + +func (c *GoProxyClient) GetVersions(path string) ([]*semver.Version, error) { + path = escapePath(path) + data, err := c.query(fmt.Sprintf(getVersionsFmt, path)) + if err != nil { + return nil, err + } + rawVersions := strings.Split(string(data), "\n") + versions := make([]*semver.Version, 0, len(rawVersions)) + for _, raw := range rawVersions { + if raw == "" { + continue + } + v, err := semver.NewVersion(raw) + if err != nil { + return nil, err + } + versions = append(versions, v) + } + return versions, nil +} + +func (c *GoProxyClient) GetModFile(path string, version *semver.Version) ([]byte, error) { + urlPath := fmt.Sprintf(getModFileFmt, escapePath(path), version) + return c.query(urlPath) +} + +func (c *GoProxyClient) query(urlPath string) ([]byte, error) { + resp, err := c.http.Get(c.apiURL.JoinPath(urlPath).String()) + if err != nil { + return nil, err + } + if resp.StatusCode != http.StatusOK { + data, _ := io.ReadAll(resp.Body) + return nil, errors.Errorf( + "unexpected response status code from %s %s: %d, body: %s", + http.MethodGet, resp.Request.URL.String(), resp.StatusCode, string(data)) + } + defer func() { _ = resp.Body.Close() }() + return io.ReadAll(resp.Body) +} + +var uppercaseRegex = regexp.MustCompile(`[A-Z]`) + +func escapePath(path string) string { + // Escape uppercase characters by converting them to lowercase and prefixing with '!' as per GOPROXY spec. + path = uppercaseRegex.ReplaceAllStringFunc(path, func(s string) string { + return "!" + strings.ToLower(s) + }) + return url.PathEscape(path) +} diff --git a/internal/module.go b/internal/module.go new file mode 100644 index 0000000..56125c9 --- /dev/null +++ b/internal/module.go @@ -0,0 +1,77 @@ +package internal + +import ( + "fmt" + "slices" + "time" + + "github.com/Masterminds/semver" + + "golang.org/x/mod/modfile" +) + +const ProgramName = "go-libyear" + +// Module is a container used to decode GOPROXY and 'go list' responses +// and transport calculated metrics. +type Module struct { + Path string `json:"Path"` + Version *semver.Version `json:"Version"` + Time time.Time `json:"Time"` + + IsIndirect bool `json:"-"` + IsFresh bool `json:"-"` + Latest *Module `json:"-"` + Libyear float64 `json:"-"` + // ReleasesDiff is the number of release versions between latest and current. + ReleasesDiff int `json:"-"` + // VersionsDiff is an array of 3 elements: major, minor and patch versions. + VersionsDiff VersionsDiff `json:"-"` +} + +type VersionsDiff [3]int64 + +func (v VersionsDiff) String() string { + return fmt.Sprintf("[%d, %d, %d]", v[0], v[1], v[2]) +} + +func (v VersionsDiff) Add(y VersionsDiff) VersionsDiff { + result := VersionsDiff{} + for i := 0; i < 3; i++ { + result[i] = v[i] + y[i] + } + return result +} + +func ReadGoMod(content []byte) (mainModule *Module, modules []*Module, err error) { + // Parse the go.mod file. + modFile, err := modfile.Parse("go.mod", content, nil) + if err != nil { + return nil, nil, err + } + + modules = make([]*Module, 0, len(modFile.Require)) + // List all dependencies, including any replace blocks, from the parsed go.mod file. + for _, require := range modFile.Require { + // Filter out replaced modules. + if slices.ContainsFunc(modFile.Replace, func(replaced *modfile.Replace) bool { + return replaced.Old.Path == require.Mod.Path + }) { + continue + } + version, err := semver.NewVersion(require.Mod.Version) + if err != nil { + return nil, nil, err + } + modules = append(modules, &Module{ + Path: require.Mod.Path, + Version: version, + IsIndirect: require.Indirect, + }) + } + if modFile.Module == nil { + return nil, nil, fmt.Errorf("go.mod file does not contain module declaration") + } + mainModule = &Module{Path: modFile.Module.Mod.Path} + return mainModule, modules, nil +} diff --git a/output.go b/output.go new file mode 100644 index 0000000..24d7ada --- /dev/null +++ b/output.go @@ -0,0 +1,149 @@ +package libyear + +import ( + "encoding/csv" + "encoding/json" + "fmt" + "os" + "strconv" + "time" + + "github.com/nieomylnieja/go-libyear/internal" +) + +type Summary struct { + Modules []*internal.Module + Main *internal.Module + releases bool + versions bool +} + +type Output interface { + Send(summary Summary) error +} + +type TableOutput struct{} + +func (p TableOutput) Send(summary Summary) error { + data := convertSummaryToTable(summary) + columnWidths := make([]int, len(data[0])) + for _, row := range data { + for i, cell := range row { + if len(cell) > columnWidths[i] { + columnWidths[i] = len(cell) + } + } + } + for _, row := range data { + for i, cell := range row { + if i == len(row)-1 { + fmt.Print(cell) + break + } + fmt.Printf("%-*s ", columnWidths[i], cell) + } + fmt.Println() + } + return nil +} + +type CSVOutput struct{} + +func (p CSVOutput) Send(summary Summary) error { + w := csv.NewWriter(os.Stdout) + return w.WriteAll(convertSummaryToTable(summary)) +} + +const timeFmt = time.DateOnly + +func convertSummaryToTable(summary Summary) [][]string { + t := [][]string{ + {"package", "version", "date", "latest", "latest_date", "libyear"}, + } + if summary.releases { + t[0] = append(t[0], "releases") + } + if summary.versions { + t[0] = append(t[0], "versions") + } + addRow := func(m *internal.Module) { + row := []string{ + m.Path, // 0 + "", // 1 + m.Time.Format(timeFmt), // 2 + "", // 3 + "", // 4 + strconv.FormatFloat(m.Libyear, 'f', 2, 64), // 5 + } + if m.Version != nil { + row[1] = m.Version.String() + } + if m.Latest != nil { + row[3] = m.Latest.Version.String() + row[4] = m.Latest.Time.Format(timeFmt) + } + if summary.releases { + row = append(row, strconv.Itoa(m.ReleasesDiff)) + } + if summary.versions { + row = append(row, m.VersionsDiff.String()) + } + t = append(t, row) + } + addRow(summary.Main) + for _, module := range summary.Modules { + addRow(module) + } + return t +} + +type JSONOutput struct{} + +type jsonSummaryModel struct { + Module string `json:"module"` + Date string `json:"date"` + Libyear float64 `json:"libyear"` + Packages []jsonPackageModel `json:"packages"` +} + +type jsonPackageModel struct { + Package string `json:"package"` + Version string `json:"version"` + Date string `json:"date"` + LatestVersion string `json:"latest_version"` + LatestDate string `json:"latest_date"` + Libyear float64 `json:"libyear"` + Releases *int `json:"releases,omitempty"` + Versions internal.VersionsDiff `json:"versions,omitempty"` +} + +func (j JSONOutput) Send(summary Summary) error { + model := jsonSummaryModel{ + Module: summary.Main.Path, + Date: summary.Main.Time.Format(timeFmt), + Libyear: summary.Main.Libyear, + Packages: make([]jsonPackageModel, 0, len(summary.Modules)), + } + for _, module := range summary.Modules { + m := jsonPackageModel{ + Package: module.Path, + Version: module.Version.String(), + Date: module.Time.Format(timeFmt), + LatestVersion: module.Latest.Version.String(), + LatestDate: module.Latest.Time.Format(timeFmt), + Libyear: module.Libyear, + } + if summary.releases { + m.Releases = ptr(module.ReleasesDiff) + } + if summary.versions { + m.Versions = module.VersionsDiff + } + model.Packages = append(model.Packages, m) + } + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(model) +} + +func ptr[T any](v T) *T { return &v } diff --git a/package.json b/package.json new file mode 100644 index 0000000..0883e35 --- /dev/null +++ b/package.json @@ -0,0 +1,13 @@ +{ + "private": true, + "type": "module", + "devDependencies": { + "cspell": "8.1.2", + "markdownlint-cli": "0.37.0", + "yaml": "2.3.4" + }, + "scripts": { + "format-cspell-config": "node ./scripts/format-cspell-config.js" + }, + "packageManager": "yarn@1.22.21" +} diff --git a/scripts/check-formatting.sh b/scripts/check-formatting.sh new file mode 100755 index 0000000..6c2371e --- /dev/null +++ b/scripts/check-formatting.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash + +set -e + +TMP_DIR=$(mktemp -d) + +cleanup_git() { + git -C "$TMP_DIR" clean -df + git -C "$TMP_DIR" checkout -- . +} + +main() { + cp -r . "$TMP_DIR" + cleanup_git + + make -C "$TMP_DIR" format + + CHANGED=$(git -C "$TMP_DIR" diff --name-only) + if [ -n "${CHANGED}" ]; then + printf >&2 "The following file(s) are not formatted:\n%s\n" "$CHANGED" + exit 1 + else + echo "Looks good!" + fi +} + +main "$@" diff --git a/scripts/check-trailing-whitespaces.bash b/scripts/check-trailing-whitespaces.bash new file mode 100755 index 0000000..80b3bb8 --- /dev/null +++ b/scripts/check-trailing-whitespaces.bash @@ -0,0 +1,20 @@ +#!/usr/bin/env bash + +found=0 +for file in $(git ls-tree -r HEAD --name-only); do + if [ ! -f "$file" ]; then + continue + fi + if grep -qE ' +$' "$file"; then + if ((found != 1)); then + echo "Trailing whitespaces found!" >&2 + fi + grep -nE ' +$' "$file" | awk -F: '{print $1}' | while IFS= read -r line; do + echo "$file:$line" >&2 + done + found=1 + fi +done +if ((found == 1)); then + exit 1 +fi \ No newline at end of file diff --git a/scripts/ensure_installed.sh b/scripts/ensure_installed.sh new file mode 100755 index 0000000..4749beb --- /dev/null +++ b/scripts/ensure_installed.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -e + +LOCAL_BIN_DIR="${LOCAL_BIN_DIR:-./bin}" + +_binary() { + if [ ! -f "${LOCAL_BIN_DIR}/${1}" ]; then + echo "$1 was not found in $LOCAL_BIN_DIR" >&2 + make "install/$1" + fi +} + +# It's cheaper to run yarn install then do any other checks. +_yarn() { + make "install/yarn" +} + +case "$1" in + binary) _binary "$2" ;; + yarn) _yarn "$2" ;; + *) echo "invalid source provided: $1" >&2 && exit 1 ;; +esac diff --git a/scripts/format-cspell-config.js b/scripts/format-cspell-config.js new file mode 100644 index 0000000..0304779 --- /dev/null +++ b/scripts/format-cspell-config.js @@ -0,0 +1,30 @@ +/* + Formatter which works on cspell config file and: + - Sorts the 'words' list. + - Removes duplicates from 'words' list. +*/ + +import YAML from 'yaml'; +import { readFileSync, writeFileSync } from 'fs'; + +const CSPELL_CONFIG = "cspell.yaml" + +function format() { + const f = readFileSync(CSPELL_CONFIG, 'utf8') + const yaml = YAML.parseDocument(f, { keepSourceTokens: true }) + + let words = yaml.get('words') + words.items.sort() + let set = new Set() + words.items = words.items.filter((w) => { + if (!set.has(w.value)) { + set.add(w.value) + return true + } + return false + }) + + writeFileSync(CSPELL_CONFIG, yaml.toString()) +} + +try { format() } catch (err) { console.error(err) } diff --git a/scripts/makefile-help.awk b/scripts/makefile-help.awk new file mode 100755 index 0000000..0e601c1 --- /dev/null +++ b/scripts/makefile-help.awk @@ -0,0 +1,18 @@ +#!/usr/bin/awk -f + +BEGIN { + FS = ":" + printf "Targets:\n" +} + +!/^##/ && f > 0 { + printf " \033[36m%-30s\033[0m %s\n", $1, r + f = 0 + r = "" +} +/^##/ { + f = f + 1 + sub(/^## /,"",$0) +} +f == 1 { r = $0 } +f > 1 { r = r " " $0 } \ No newline at end of file diff --git a/source.go b/source.go new file mode 100644 index 0000000..06540a1 --- /dev/null +++ b/source.go @@ -0,0 +1,89 @@ +package libyear + +import ( + "io" + "net/http" + "net/url" + "os" + "strings" + + "github.com/Masterminds/semver" + + "github.com/pkg/errors" +) + +type Source interface { + Read() ([]byte, error) +} + +type PkgSource struct { + Pkg string + repo ModulesRepo +} + +func (p *PkgSource) Read() ([]byte, error) { + path := p.Pkg + var version *semver.Version + if strings.Contains(p.Pkg, "@") { + split := strings.Split(path, "@") + if len(split) != 2 { + return nil, errors.New("invalid pkg name provided, expected version after @ char") + } + path = split[0] + var err error + version, err = semver.NewVersion(split[1]) + if err != nil { + return nil, err + } + } else { + // .mod endpoint does not support 'latest' version literal, we need an exact semver. + latest, err := p.repo.GetLatestInfo(path) + if err != nil { + return nil, err + } + version = latest.Version + } + return p.repo.GetModFile(path, version) +} + +func (p *PkgSource) SetModulesRepo(repo ModulesRepo) { + p.repo = repo +} + +type URLSource struct { + HTTP http.Client + RawURL string +} + +func (s URLSource) Read() ([]byte, error) { + u, err := url.Parse(s.RawURL) + if err != nil { + return nil, err + } + resp, err := s.HTTP.Get(u.String()) + if err != nil { + return nil, err + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode != http.StatusOK { + data, _ := io.ReadAll(resp.Body) + return nil, errors.Errorf( + "unexpected response status code: %d, body: %s", + resp.StatusCode, string(data)) + } + return io.ReadAll(resp.Body) +} + +type FileSource struct { + Path string +} + +func (s FileSource) Read() ([]byte, error) { + return os.ReadFile(s.Path) +} + +type StdinSource struct{} + +func (s StdinSource) Read() ([]byte, error) { + return io.ReadAll(os.Stdin) +} diff --git a/test/bats b/test/bats new file mode 160000 index 0000000..e9fd17a --- /dev/null +++ b/test/bats @@ -0,0 +1 @@ +Subproject commit e9fd17a70721e447313691f239d297cecea6dfb7 diff --git a/test/inputs/generate_responses.sh b/test/inputs/generate_responses.sh new file mode 100755 index 0000000..480955d --- /dev/null +++ b/test/inputs/generate_responses.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash + +# Helper script to generate responses.json based on a list of repositories. + +set -eo pipefail + +test_go_mod="github.com/test/test" + +repos=( + github.com/pkg/errors + golang.org/x/sync + github.com/cpuguy83/go-md2man/v2 + github.com/xrash/smetrics + github.com/BurntSushi/toml +) + +json="" +for repo in "${repos[@]}"; do + versions=$(go list -m -json -versions "$repo" | jq .Versions) + if [[ $versions == "null" ]];then + versions=$(curl --silent "https://api.deps.dev/v3alpha/systems/go/packages/${repo//\//%2F}" | + jq -c [.versions[].versionKey.version]) + fi + + escaped_repo=$(sed 's/[A-Z]/!\L&/g' <<<"$repo") + + info_endpoints=$(for version in $(jq -r .[] <<<"$versions"); do + go list -m -json "$repo@$version" | jq ' + {([ + "'"$escaped_repo"'", + "@v", + (.Version) + ".info" + ] | join("/")): {"Path": (.Path), "Version": (.Version), "Time": .Time}}' + done | jq -s add) + + latest_version=$(jq -r .[-1] <<<"$versions") + latest_time=$(jq -r 'to_entries | .[-1].value.Time' <<<"$info_endpoints") + latest_endpoint=$(jq -n "{([ + \"$escaped_repo\", + \"@latest\" + ] | join(\"/\")): {\"Path\": \"$repo\", \"Version\": \"$latest_version\", \"Time\": \"$latest_time\"}}") + + list_endpoint=$(jq "{([ + \"$escaped_repo\", + \"@v\", + \"list\" + ] | join(\"/\")): (. | join(\"\n\"))}" <<<"$versions") + + json="$json $info_endpoints $latest_endpoint $list_endpoint" +done + +# We need .info and .mod for our test go.mod +json="$json {\"${test_go_mod}/@latest\": \"v1.0.0\"} {\"${test_go_mod}/@v/v1.0.0.mod\": \"./test/inputs/go.mod\"}" + +jq -s 'reduce .[] as $obj ({}; . * $obj)' <<<"$json" \ No newline at end of file diff --git a/test/inputs/go.mod b/test/inputs/go.mod new file mode 100644 index 0000000..2b15535 --- /dev/null +++ b/test/inputs/go.mod @@ -0,0 +1,14 @@ +module github.com/test/test + +go 1.21 + +require ( + golang.org/x/sync v0.5.0 + github.com/pkg/errors v0.8.0 + github.com/BurntSushi/toml v0.4.1 +) + +require ( + github.com/cpuguy83/go-md2man/v2 v2.0.1 // indirect + github.com/xrash/smetrics v0.0.0-20200723181607-f06e43cca1ab // indirect +) \ No newline at end of file diff --git a/test/inputs/go.sum b/test/inputs/go.sum new file mode 100644 index 0000000..89cf87f --- /dev/null +++ b/test/inputs/go.sum @@ -0,0 +1,6 @@ +github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/xrash/smetrics v0.0.0-20200723181607-f06e43cca1ab/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8= +golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= diff --git a/test/inputs/responses.json b/test/inputs/responses.json new file mode 100644 index 0000000..d77d369 --- /dev/null +++ b/test/inputs/responses.json @@ -0,0 +1,229 @@ +{ + "github.com/pkg/errors/@v/v0.1.0.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.1.0", + "Time": "2016-04-24T12:18:34Z" + }, + "github.com/pkg/errors/@v/v0.2.0.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.2.0", + "Time": "2016-04-25T04:42:03Z" + }, + "github.com/pkg/errors/@v/v0.3.0.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.3.0", + "Time": "2016-05-02T19:39:29Z" + }, + "github.com/pkg/errors/@v/v0.4.0.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.4.0", + "Time": "2016-05-10T21:41:07Z" + }, + "github.com/pkg/errors/@v/v0.5.0.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.5.0", + "Time": "2016-05-23T09:19:03Z" + }, + "github.com/pkg/errors/@v/v0.5.1.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.5.1", + "Time": "2016-05-24T02:36:43Z" + }, + "github.com/pkg/errors/@v/v0.6.0.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.6.0", + "Time": "2016-06-07T07:26:48Z" + }, + "github.com/pkg/errors/@v/v0.7.0.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.7.0", + "Time": "2016-06-13T02:17:47Z" + }, + "github.com/pkg/errors/@v/v0.7.1.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.7.1", + "Time": "2016-08-22T09:00:10Z" + }, + "github.com/pkg/errors/@v/v0.8.0.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.8.0", + "Time": "2016-09-29T01:48:01Z" + }, + "github.com/pkg/errors/@v/v0.8.1.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.8.1", + "Time": "2019-01-03T06:52:24Z" + }, + "github.com/pkg/errors/@v/v0.9.0.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.9.0", + "Time": "2020-01-07T21:33:24Z" + }, + "github.com/pkg/errors/@v/v0.9.1.info": { + "Path": "github.com/pkg/errors", + "Version": "v0.9.1", + "Time": "2020-01-14T19:47:44Z" + }, + "github.com/pkg/errors/@latest": { + "Path": "github.com/pkg/errors", + "Version": "v0.9.1", + "Time": "2020-01-14T19:47:44Z" + }, + "github.com/pkg/errors/@v/list": "v0.1.0\nv0.2.0\nv0.3.0\nv0.4.0\nv0.5.0\nv0.5.1\nv0.6.0\nv0.7.0\nv0.7.1\nv0.8.0\nv0.8.1\nv0.9.0\nv0.9.1", + "golang.org/x/sync/@v/v0.1.0.info": { + "Path": "golang.org/x/sync", + "Version": "v0.1.0", + "Time": "2022-09-29T20:41:14Z" + }, + "golang.org/x/sync/@v/v0.2.0.info": { + "Path": "golang.org/x/sync", + "Version": "v0.2.0", + "Time": "2023-04-19T16:11:59Z" + }, + "golang.org/x/sync/@v/v0.3.0.info": { + "Path": "golang.org/x/sync", + "Version": "v0.3.0", + "Time": "2023-06-01T20:35:10Z" + }, + "golang.org/x/sync/@v/v0.4.0.info": { + "Path": "golang.org/x/sync", + "Version": "v0.4.0", + "Time": "2023-09-26T16:46:49Z" + }, + "golang.org/x/sync/@v/v0.5.0.info": { + "Path": "golang.org/x/sync", + "Version": "v0.5.0", + "Time": "2023-10-11T14:04:17Z" + }, + "golang.org/x/sync/@latest": { + "Path": "golang.org/x/sync", + "Version": "v0.5.0", + "Time": "2023-10-11T14:04:17Z" + }, + "golang.org/x/sync/@v/list": "v0.1.0\nv0.2.0\nv0.3.0\nv0.4.0\nv0.5.0", + "github.com/cpuguy83/go-md2man/v2/@v/v2.0.0.info": { + "Path": "github.com/cpuguy83/go-md2man/v2", + "Version": "v2.0.0", + "Time": "2019-03-14T23:30:15Z" + }, + "github.com/cpuguy83/go-md2man/v2/@v/v2.0.1.info": { + "Path": "github.com/cpuguy83/go-md2man/v2", + "Version": "v2.0.1", + "Time": "2021-07-16T23:20:56Z" + }, + "github.com/cpuguy83/go-md2man/v2/@v/v2.0.2.info": { + "Path": "github.com/cpuguy83/go-md2man/v2", + "Version": "v2.0.2", + "Time": "2022-04-22T22:25:44Z" + }, + "github.com/cpuguy83/go-md2man/v2/@v/v2.0.3.info": { + "Path": "github.com/cpuguy83/go-md2man/v2", + "Version": "v2.0.3", + "Time": "2023-10-10T18:05:46Z" + }, + "github.com/cpuguy83/go-md2man/v2/@latest": { + "Path": "github.com/cpuguy83/go-md2man/v2", + "Version": "v2.0.3", + "Time": "2023-10-10T18:05:46Z" + }, + "github.com/cpuguy83/go-md2man/v2/@v/list": "v2.0.0\nv2.0.1\nv2.0.2\nv2.0.3", + "github.com/xrash/smetrics/@v/v0.0.0-20170218160415-a3153f7040e9.info": { + "Path": "github.com/xrash/smetrics", + "Version": "v0.0.0-20170218160415-a3153f7040e9", + "Time": "2017-02-18T16:04:15Z" + }, + "github.com/xrash/smetrics/@v/v0.0.0-20200723181607-f06e43cca1ab.info": { + "Path": "github.com/xrash/smetrics", + "Version": "v0.0.0-20200723181607-f06e43cca1ab", + "Time": "2020-07-23T18:16:07Z" + }, + "github.com/xrash/smetrics/@v/v0.0.0-20200730060457-89a2a8a1fb0b.info": { + "Path": "github.com/xrash/smetrics", + "Version": "v0.0.0-20200730060457-89a2a8a1fb0b", + "Time": "2020-07-30T06:04:57Z" + }, + "github.com/xrash/smetrics/@v/v0.0.0-20201216005158-039620a65673.info": { + "Path": "github.com/xrash/smetrics", + "Version": "v0.0.0-20201216005158-039620a65673", + "Time": "2020-12-16T00:51:58Z" + }, + "github.com/xrash/smetrics/@latest": { + "Path": "github.com/xrash/smetrics", + "Version": "v0.0.0-20201216005158-039620a65673", + "Time": "2020-12-16T00:51:58Z" + }, + "github.com/xrash/smetrics/@v/list": "v0.0.0-20170218160415-a3153f7040e9\nv0.0.0-20200723181607-f06e43cca1ab\nv0.0.0-20200730060457-89a2a8a1fb0b\nv0.0.0-20201216005158-039620a65673", + "github.com/!burnt!sushi/toml/@v/v0.1.0.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v0.1.0", + "Time": "2014-07-17T22:42:52Z" + }, + "github.com/!burnt!sushi/toml/@v/v0.2.0.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v0.2.0", + "Time": "2016-03-09T02:19:12Z" + }, + "github.com/!burnt!sushi/toml/@v/v0.3.0.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v0.3.0", + "Time": "2017-03-28T06:15:53Z" + }, + "github.com/!burnt!sushi/toml/@v/v0.3.1.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v0.3.1", + "Time": "2018-08-15T10:47:33Z" + }, + "github.com/!burnt!sushi/toml/@v/v0.4.0.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v0.4.0", + "Time": "2021-08-02T07:59:22Z" + }, + "github.com/!burnt!sushi/toml/@v/v0.4.1.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v0.4.1", + "Time": "2021-08-05T08:14:45Z" + }, + "github.com/!burnt!sushi/toml/@v/v1.0.0.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v1.0.0", + "Time": "2022-01-12T06:57:21Z" + }, + "github.com/!burnt!sushi/toml/@v/v1.1.0.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v1.1.0", + "Time": "2022-04-04T19:53:34Z" + }, + "github.com/!burnt!sushi/toml/@v/v1.2.0.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v1.2.0", + "Time": "2022-06-25T23:55:26Z" + }, + "github.com/!burnt!sushi/toml/@v/v1.2.1.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v1.2.1", + "Time": "2022-10-22T08:23:34Z" + }, + "github.com/!burnt!sushi/toml/@v/v1.3.0.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v1.3.0", + "Time": "2023-05-30T15:10:12Z" + }, + "github.com/!burnt!sushi/toml/@v/v1.3.1.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v1.3.1", + "Time": "2023-06-06T09:25:54Z" + }, + "github.com/!burnt!sushi/toml/@v/v1.3.2.info": { + "Path": "github.com/BurntSushi/toml", + "Version": "v1.3.2", + "Time": "2023-06-08T06:14:45Z" + }, + "github.com/!burnt!sushi/toml/@latest": { + "Path": "github.com/BurntSushi/toml", + "Version": "v1.3.2", + "Time": "2023-06-08T06:14:45Z" + }, + "github.com/!burnt!sushi/toml/@v/list": "v0.1.0\nv0.2.0\nv0.3.0\nv0.3.1\nv0.4.0\nv0.4.1\nv1.0.0\nv1.1.0\nv1.2.0\nv1.2.1\nv1.3.0\nv1.3.1\nv1.3.2", + "github.com/test/test/@latest": "v1.0.0", + "github.com/test/test/@v/v1.0.0.mod": "./test/inputs/go.mod" +} diff --git a/test/outputs/all_details_for_all_dependencies b/test/outputs/all_details_for_all_dependencies new file mode 100644 index 0000000..ac189ca --- /dev/null +++ b/test/outputs/all_details_for_all_dependencies @@ -0,0 +1,7 @@ +package version date latest latest_date libyear releases versions +github.com/test/test $MAIN_DATE 7.77 14 [1, 1, 2] +golang.org/x/sync 0.5.0 2023-10-11 0.5.0 2023-10-11 0.00 0 [0, 0, 0] +github.com/pkg/errors 0.8.0 2016-09-29 0.9.1 2020-01-14 3.30 3 [0, 1, 0] +github.com/BurntSushi/toml 0.4.1 2021-08-05 1.3.2 2023-06-08 1.84 7 [1, 0, 0] +github.com/cpuguy83/go-md2man/v2 2.0.1 2021-07-16 2.0.3 2023-10-10 2.24 2 [0, 0, 2] +github.com/xrash/smetrics 0.0.0-20200723181607-f06e43cca1ab 2020-07-23 0.0.0-20201216005158-039620a65673 2020-12-16 0.40 2 [0, 0, 0] diff --git a/test/outputs/basic_usage b/test/outputs/basic_usage new file mode 100644 index 0000000..d39ef2a --- /dev/null +++ b/test/outputs/basic_usage @@ -0,0 +1,5 @@ +package version date latest latest_date libyear +github.com/test/test $MAIN_DATE 5.14 +golang.org/x/sync 0.5.0 2023-10-11 0.5.0 2023-10-11 0.00 +github.com/pkg/errors 0.8.0 2016-09-29 0.9.1 2020-01-14 3.30 +github.com/BurntSushi/toml 0.4.1 2021-08-05 1.3.2 2023-06-08 1.84 diff --git a/test/outputs/modules_cache b/test/outputs/modules_cache new file mode 100644 index 0000000..15373e1 --- /dev/null +++ b/test/outputs/modules_cache @@ -0,0 +1,5 @@ +{"path":"golang.org/x/sync","version":"0.5.0","time":"2023-10-11T14:04:17Z"} +{"path":"github.com/pkg/errors","version":"0.8.0","time":"2016-09-29T01:48:01Z"} +{"path":"github.com/BurntSushi/toml","version":"0.4.1","time":"2021-08-05T08:14:45Z"} +{"path":"github.com/pkg/errors","version":"0.9.1","time":"2020-01-14T19:47:44Z"} +{"path":"github.com/BurntSushi/toml","version":"1.3.2","time":"2023-06-08T06:14:45Z"} diff --git a/test/outputs/output.csv b/test/outputs/output.csv new file mode 100644 index 0000000..8683d90 --- /dev/null +++ b/test/outputs/output.csv @@ -0,0 +1,5 @@ +package,version,date,latest,latest_date,libyear,releases,versions +github.com/test/test,,$MAIN_DATE,,,5.14,10,"[1, 1, 0]" +golang.org/x/sync,0.5.0,2023-10-11,0.5.0,2023-10-11,0.00,0,"[0, 0, 0]" +github.com/pkg/errors,0.8.0,2016-09-29,0.9.1,2020-01-14,3.30,3,"[0, 1, 0]" +github.com/BurntSushi/toml,0.4.1,2021-08-05,1.3.2,2023-06-08,1.84,7,"[1, 0, 0]" diff --git a/test/outputs/output.json b/test/outputs/output.json new file mode 100644 index 0000000..f2b00ac --- /dev/null +++ b/test/outputs/output.json @@ -0,0 +1,49 @@ +{ + "module": "github.com/test/test", + "date": "$MAIN_DATE", + "libyear": 5.136072520294267, + "packages": [ + { + "package": "golang.org/x/sync", + "version": "0.5.0", + "date": "2023-10-11", + "latest_version": "0.5.0", + "latest_date": "2023-10-11", + "libyear": 0, + "releases": 0, + "versions": [ + 0, + 0, + 0 + ] + }, + { + "package": "github.com/pkg/errors", + "version": "0.8.0", + "date": "2016-09-29", + "latest_version": "0.9.1", + "latest_date": "2020-01-14", + "libyear": 3.295204940385591, + "releases": 3, + "versions": [ + 0, + 1, + 0 + ] + }, + { + "package": "github.com/BurntSushi/toml", + "version": "0.4.1", + "date": "2021-08-05", + "latest_version": "1.3.2", + "latest_date": "2023-06-08", + "libyear": 1.8408675799086758, + "releases": 7, + "versions": [ + 1, + 0, + 0 + ] + } + ] +} diff --git a/test/outputs/show_indirect b/test/outputs/show_indirect new file mode 100644 index 0000000..f45d331 --- /dev/null +++ b/test/outputs/show_indirect @@ -0,0 +1,7 @@ +package version date latest latest_date libyear +github.com/test/test $MAIN_DATE 7.77 +golang.org/x/sync 0.5.0 2023-10-11 0.5.0 2023-10-11 0.00 +github.com/pkg/errors 0.8.0 2016-09-29 0.9.1 2020-01-14 3.30 +github.com/BurntSushi/toml 0.4.1 2021-08-05 1.3.2 2023-06-08 1.84 +github.com/cpuguy83/go-md2man/v2 2.0.1 2021-07-16 2.0.3 2023-10-10 2.24 +github.com/xrash/smetrics 0.0.0-20200723181607-f06e43cca1ab 2020-07-23 0.0.0-20201216005158-039620a65673 2020-12-16 0.40 diff --git a/test/outputs/show_releases b/test/outputs/show_releases new file mode 100644 index 0000000..49b64fd --- /dev/null +++ b/test/outputs/show_releases @@ -0,0 +1,5 @@ +package version date latest latest_date libyear releases +github.com/test/test $MAIN_DATE 5.14 10 +golang.org/x/sync 0.5.0 2023-10-11 0.5.0 2023-10-11 0.00 0 +github.com/pkg/errors 0.8.0 2016-09-29 0.9.1 2020-01-14 3.30 3 +github.com/BurntSushi/toml 0.4.1 2021-08-05 1.3.2 2023-06-08 1.84 7 diff --git a/test/outputs/show_versions b/test/outputs/show_versions new file mode 100644 index 0000000..8d4687b --- /dev/null +++ b/test/outputs/show_versions @@ -0,0 +1,5 @@ +package version date latest latest_date libyear versions +github.com/test/test $MAIN_DATE 5.14 [1, 1, 0] +golang.org/x/sync 0.5.0 2023-10-11 0.5.0 2023-10-11 0.00 [0, 0, 0] +github.com/pkg/errors 0.8.0 2016-09-29 0.9.1 2020-01-14 3.30 [0, 1, 0] +github.com/BurntSushi/toml 0.4.1 2021-08-05 1.3.2 2023-06-08 1.84 [1, 0, 0] diff --git a/test/outputs/skip_fresh b/test/outputs/skip_fresh new file mode 100644 index 0000000..8f9b464 --- /dev/null +++ b/test/outputs/skip_fresh @@ -0,0 +1,4 @@ +package version date latest latest_date libyear +github.com/test/test $MAIN_DATE 5.14 +github.com/pkg/errors 0.8.0 2016-09-29 0.9.1 2020-01-14 3.30 +github.com/BurntSushi/toml 0.4.1 2021-08-05 1.3.2 2023-06-08 1.84 diff --git a/test/outputs/skip_fresh_show_indirect b/test/outputs/skip_fresh_show_indirect new file mode 100644 index 0000000..ec0f0c2 --- /dev/null +++ b/test/outputs/skip_fresh_show_indirect @@ -0,0 +1,6 @@ +package version date latest latest_date libyear +github.com/test/test $MAIN_DATE 7.77 +github.com/pkg/errors 0.8.0 2016-09-29 0.9.1 2020-01-14 3.30 +github.com/BurntSushi/toml 0.4.1 2021-08-05 1.3.2 2023-06-08 1.84 +github.com/cpuguy83/go-md2man/v2 2.0.1 2021-07-16 2.0.3 2023-10-10 2.24 +github.com/xrash/smetrics 0.0.0-20200723181607-f06e43cca1ab 2020-07-23 0.0.0-20201216005158-039620a65673 2020-12-16 0.40 diff --git a/test/test.bats b/test/test.bats new file mode 100644 index 0000000..718991d --- /dev/null +++ b/test/test.bats @@ -0,0 +1,221 @@ +# setup_file is run once for the whole file. +setup_file() { + load "test_helper/bats-support/load" + load "test_helper/bats-assert/load" + + PKG="main" + LD_FLAGS="$( + cat <&1 + assert_output --partial "USAGE:" + done +} + +@test "version flag" { + for alias in --version -v; do + run go-libyear "$alias" + assert_output - <