diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..43decc1
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,15 @@
+root = true
+
+[*]
+indent_style = space
+indent_size = 2
+charset = utf-8
+trim_trailing_whitespace = true
+insert_final_newline = true
+end_of_line = lf
+
+[*.md]
+trim_trailing_whitespace = false
+
+[Makefile]
+indent_style = tab
diff --git a/.envrc b/.envrc
new file mode 100644
index 0000000..1d953f4
--- /dev/null
+++ b/.envrc
@@ -0,0 +1 @@
+use nix
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..cbaf00a
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,36 @@
+name: Release
+
+on:
+ push:
+ tags:
+ - 'v*'
+
+permissions:
+ contents: write
+
+env:
+ GO_VERSION: '1.19.2'
+
+jobs:
+ tests:
+ uses: ./.github/workflows/test.yml
+ goreleaser:
+ runs-on: ubuntu-latest
+ needs: tests
+ timeout-minutes: 10
+ steps:
+ - uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
+ - uses: actions/setup-go@v3
+ with:
+ go-version: ${{ env.GO_VERSION }}
+ cache: true
+ - name: Run GoReleaser
+ uses: goreleaser/goreleaser-action@v3
+ with:
+ distribution: goreleaser
+ version: latest
+ args: release --rm-dist
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
new file mode 100644
index 0000000..290a696
--- /dev/null
+++ b/.github/workflows/test.yml
@@ -0,0 +1,35 @@
+name: Test
+
+on:
+ pull_request:
+ paths-ignore:
+ - 'README.md'
+ workflow_call:
+
+permissions:
+ contents: read
+
+env:
+ GO_VERSION: '1.19.2'
+
+jobs:
+ build:
+ name: Build
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/setup-go@v3
+ with:
+ go-version: ${{ env.GO_VERSION }}
+ - uses: actions/checkout@v3
+ - run: make build
+
+ test:
+ name: Test
+ needs: build
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: cachix/install-nix-action@v18
+ - uses: actions/checkout@v3
+ - run: nix-shell --pure --command "make test"
diff --git a/.gitignore b/.gitignore
index 969019b..74235a2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,4 @@
knega
+notes.md
+
+dist/
diff --git a/.gometalinter.json b/.gometalinter.json
deleted file mode 100644
index 76da388..0000000
--- a/.gometalinter.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "Aggregate": true,
- "Deadline": "5m",
- "Sort": ["Path"],
- "Vendor": true,
- "Warn-Unmatched-Nolint": true,
- "Enable": [
- "deadcode",
- "gofmt",
- "goimports",
- "golint",
- "ineffassign",
- "misspell",
- "vet"
- ]
-}
diff --git a/.goreleaser.yaml b/.goreleaser.yaml
new file mode 100644
index 0000000..228f884
--- /dev/null
+++ b/.goreleaser.yaml
@@ -0,0 +1,27 @@
+before:
+ hooks:
+ - go mod tidy
+builds:
+ - env:
+ - CGO_ENABLED=0
+ goos:
+ - linux
+ - windows
+ - darwin
+archives:
+ - replacements:
+ darwin: Darwin
+ linux: Linux
+ windows: Windows
+ 386: i386
+ amd64: x86_64
+checksum:
+ name_template: 'checksums.txt'
+snapshot:
+ name_template: "{{ incpatch .Version }}-next"
+changelog:
+ sort: asc
+ filters:
+ exclude:
+ - '^docs:'
+ - '^test:'
diff --git a/LICENSE b/LICENSE
index d7f1051..ea33fb3 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,339 +1,21 @@
-GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Lesser General Public License instead.) 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
-this service 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 make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. 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.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-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
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the 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 a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE 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.
-
- 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
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
- {description}
- Copyright (C) {year} {fullname}
-
- 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 2 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, write to the Free Software Foundation, Inc.,
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) year name of author
- Gnomovision 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, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- {signature of Ty Coon}, 1 April 1989
- Ty Coon, President of Vice
-
-This 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.
+MIT License
+
+Copyright (c) 2019 Kristoffer Lind
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..c3e90dc
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,17 @@
+build:
+ go mod download
+ go build -v
+
+install: build
+ mv knega ~/bin
+
+test: build
+ docker-compose down
+ docker-compose up -d
+ KNEGA=../../knega KNEGA_TRACE=true KNEGA_ALLOW_INSECURE_REGISTRY=true bats --print-output-on-failure --show-output-of-passing-tests test
+ docker-compose down
+
+test-release:
+ goreleaser release --rm-dist --skip-publish --snapshot
+
+.PHONY: build install test-release
diff --git a/README.md b/README.md
index 2fd4112..d4ed6ae 100644
--- a/README.md
+++ b/README.md
@@ -1,46 +1,11 @@
# Knega
-CLI tool for commonly used generic CI/CD steps (analyze, build and deploy actions) and monorepo actions.
+Minimalist cli tool for building many similar components in a monorepo. Calculates a hash of the file content of a component and checks for existing artifacts with that hash to determine whether to build the component.
-## Usage
-Tool has help sections describing all the different actions, overview found by running `knega`
-
-### Troubleshooting builds
-`KNEGA_TRACE=true` set as environment variable will enable trace mode.
-
-### Examples
-#### Monorepo actions
-Example configurations can be found in [examples/](./examples), [.knega.root.toml](./examples/.knega.root.toml) should be at project root and [.app.toml](./examples/.app.toml) should exist for every application
-
-Command | Action
---- | ---
-`knega changed ` | runs action for applications with changes (based on hash of inputs, checks whether image & chart with that hash already exists)
-`knega all ` | runs action for all applications
-`knega changed check` | runs check commands for applications with changes
-`knega changed build` | runs build commands for applications with changes
-`knega changed analyze` | runs analyze commands for applications with changes
-`knega all release` | runs release commands for all applications
-
-#### Individual actions
-Command | Action
---- | ---
-`knega chart create` | Create chart
-`knega chart upload` | Upload chart to repository
-`knega docker create` | Builds based on dockerfile if exists, otherwise tries herokuish build
-`knega docker upload` | Upload docker image to repository
-`knega docker test` | Runs tests (only works if application matches a herokuish buildpack)
+### Example configurations
+Example configurations can be found in [examples/](./examples), [.knega.root.yml](./examples/.knega.root.yml) should be at project root and [.component.yml](./examples/.component.yml) should exist for every component. Check [examples/full](./examples/full/) for an example with sample components (used by tests).
-## Inspiration
-### Individual actions
-I've had a collection of bash scripts for various generic steps for a while, I bundled them in a docker image to simplify reuse a bit but it wasn't great and had issues with needing docker dind to work (which comes with a fair bit of security issues on build servers). I wanted to learn Go and thought it would be nice to have all those tasks available in a single binary, while also enabling making them work on platforms other than linux. I haven't tested it on any other platform yet, but I'm trying to avoid OS specific stuff.
-
-### Monorepo actions
-Heavily inspired by [Baur](https://github.com/simplesurance/baur), loved the simplicity of it compared to other monorepo build tools. Most notable differences are running application pipelines in parallell and checks for changes relying on repository checks (docker image repository/helm repository) rather than a database. It also includes Check, Analyze and Release commands and makes $ROOT, $APPLICATION_NAME and $INPUTS_HASH available so that any part can be replaced except input hash generation and existence checks (might make existence checks replaceable aswell).
-
-Database being removed means you lose out on the build statistics (grafana dashboard).
-
-If what Baur does works for you, use that instead. This is my first Go project, I've currently got about 20 hours of Go experience, it's not well tested (I only know that it works for my current projects) and error handling isn't great.
-
-This does however fix the issues I had with Baur and has been a great project for learning a bit of Go.
+## Usage
+`knega changed/all ` where action is a set of commands defined in configuration. It will execute those commands for all or changed components with that action defined.
-## License
-Since parts of it is kind of a derivative work of [Baur](https://github.com/simplesurance/baur) I've also put the same license on it.
+## Development
+If you have [direnv](https://direnv.net/) and [nix package manager](https://nixos.org/) installed. You should be able to just start using commands found in Makefile. If you don't want those you can look at shell.nix to see what's needed.
diff --git a/all.go b/all.go
deleted file mode 100644
index 5ff21a6..0000000
--- a/all.go
+++ /dev/null
@@ -1,103 +0,0 @@
-package main
-
-import (
- "runtime"
- "log"
- "time"
- "sync"
-)
-
-func createWorker (workerId int, asyncWorkers *sync.WaitGroup, jobs <-chan Job, results chan<- string) {
- for job := range jobs {
- log.Printf("Worker %d: Start work on %s", workerId, job.application.name)
- startTime := time.Now()
-
- result := ""
-
- for _, jobCommand := range job.commands {
- output := executeCommand(jobCommand, job.application.path)
- if IsTrace() {
- log.Printf("%s", output)
- }
- result += output
- }
-
- endTime := time.Now()
- timeTaken := endTime.Sub(startTime)
- log.Printf("Worker %d: Successfully ran %s for %s in %s", workerId, job.action, job.application.name, timeTaken)
-
- results <- result
- }
- log.Printf("Worker %d: idle, no more jobs to pick", workerId)
- asyncWorkers.Done()
-}
-
-func createWorkerPipeline (jobs []Job, resultsChannel chan<- string) {
- jobsCount := len(jobs)
- workerCount := getMin(runtime.NumCPU(), jobsCount)
- jobsChannel := make(chan Job, jobsCount)
-
- for _, job := range jobs {
- jobsChannel <- job
- log.Printf("Created %s job for %s", job.action, job.application.name)
- }
- close(jobsChannel)
-
- var asyncWorkers sync.WaitGroup
- for workerId := 1; workerId <= workerCount; workerId++ {
- asyncWorkers.Add(1)
- go createWorker(workerId, &asyncWorkers, jobsChannel, resultsChannel)
- }
- log.Printf("Started %d workers", workerCount)
- asyncWorkers.Wait()
- close(resultsChannel)
-}
-
-func pipelineResults(results <-chan string, done chan<- bool, startTime time.Time, totalJobs int, isVerbose bool) {
- completedJobs := 0
- for result := range results {
- if isVerbose {
- log.Print(result)
- }
- completedJobs++
- currentTime := time.Now()
- log.Printf("Completed %d of %d jobs in %s", completedJobs, totalJobs, currentTime.Sub(startTime))
- }
-
- done <- true
-}
-
-func all(action string) error {
- startTime := time.Now()
- repository := initializeRepository(true)
- var jobs []Job
- for _, application := range repository.applications {
- job := createJob(repository, application, action)
- jobs = append(jobs, job)
- }
-
- done := make(chan bool, 1)
- defer close(done)
-
- results := make(chan string, len(jobs))
-
- go pipelineResults(results, done, startTime, len(jobs), false)
- createWorkerPipeline(jobs, results)
-
- <-done
-
- endTime := time.Now()
- timeTaken := endTime.Sub(startTime)
- log.Printf("Total time taken: %s", timeTaken)
-
- return nil
-}
-
-func printStatus(applications []Application) {
- for _, application := range applications {
- log.Printf("%s requires rebuild", application.name)
- }
- if len(applications) == 0 {
- log.Print("No rebuilds required")
- }
-}
diff --git a/application-configuration.go b/application-configuration.go
deleted file mode 100644
index e38d59e..0000000
--- a/application-configuration.go
+++ /dev/null
@@ -1,174 +0,0 @@
-package main
-
-import (
- "log"
- "bytes"
- "os"
-
- "github.com/spf13/viper"
-)
-
-type ApplicationConfiguration struct {
- name string
- inputs struct {
- filePaths []string
- gitFilePaths []string
- }
- environment struct {
- name string
- urls []string
- }
- artifacts []interface{} // will replace outputs
- outputs struct {
- dockerImage struct {
- idFile string
- repository string
- tag string
- usernameEnv string
- passwordEnv string
- }
- helmChart struct {
- chartPath string
- packageFilePath string
- packageFileName string
- repository string
- usernameEnv string
- passwordEnv string
- repositoryGitURL string
- }
- }
- commands struct {
- check []string
- build []string
- analyze []string
- release []string
- }
-}
-
-var defaultApplicationConfiguration = []byte(`
-[Input]
-[Input.GitFiles]
- paths = ["*"]
-`)
-
-
-func getApplicationConfiguration(configurationPath string, repository Repository) ApplicationConfiguration {
- configurationFile := getConfigurationManager(configurationPath, repository)
-
- configuration := ApplicationConfiguration{
- name: configurationFile.GetString("name"),
- }
-
- configuration.inputs.filePaths = configurationFile.GetStringSlice("Input.Files.paths")
- configuration.inputs.gitFilePaths = configurationFile.GetStringSlice("Input.GitFiles.paths")
-
- configuration.outputs.dockerImage.idFile = configurationFile.GetString("Output.DockerImage.idFile")
- configuration.outputs.dockerImage.repository = configurationFile.GetString("Output.DockerImage.repository")
- configuration.outputs.dockerImage.tag = configurationFile.GetString("Output.DockerImage.tag")
- configuration.outputs.dockerImage.usernameEnv = "KNEGA_DOCKER_USERNAME"
- configuration.outputs.dockerImage.passwordEnv = "KNEGA_DOCKER_PASSWORD"
-
- configuration.outputs.helmChart.chartPath = configurationFile.GetString("Output.HelmChart.chartPath")
- configuration.outputs.helmChart.packageFilePath = configurationFile.GetString("Output.HelmChart.packageFilePath")
- configuration.outputs.helmChart.packageFileName = configurationFile.GetString("Output.HelmChart.packageFileName")
- configuration.outputs.helmChart.repository = configurationFile.GetString("Output.HelmChart.repository")
- configuration.outputs.helmChart.usernameEnv = "KNEGA_HELM_USERNAME"
- configuration.outputs.helmChart.passwordEnv = "KNEGA_HELM_PASSWORD"
- configuration.outputs.helmChart.repositoryGitURL = configurationFile.GetString("Output.HelmChart.repositoryGitURL")
-
- configuration.commands.check = configurationFile.GetStringSlice("Check.commands")
- configuration.commands.build = configurationFile.GetStringSlice("Build.commands")
- configuration.commands.analyze = configurationFile.GetStringSlice("Analyze.commands")
- configuration.commands.release = configurationFile.GetStringSlice("Release.commands")
-
- configuration.environment.name = os.Getenv("KNEGA_ENVIRONMENT")
- if configuration.environment.name != "" {
- configuration.environment.urls = configurationFile.GetStringSlice(configuration.environment.name + ".urls")
- }
-
- configuration.artifacts = getArtifactsConfiguration(configurationFile)
-
- return configuration
-}
-
-func getConfigurationManager(configurationPath string, repository Repository) *viper.Viper {
- configurationFile := viper.New()
- configurationFile.SetConfigType("toml")
- configurationFile.ReadConfig(bytes.NewBuffer(defaultApplicationConfiguration))
-
- hasRootConfig := fileExists(repository.path + "/.knega.root.toml")
-
- if hasRootConfig {
- configurationFile.SetConfigName(".knega.root")
- configurationFile.AddConfigPath(repository.path)
- err := configurationFile.MergeInConfig()
- if err != nil {
- log.Fatal(err)
- }
- }
-
- hasApplicationConfig := fileExists(configurationPath + "/.app.toml")
-
- if hasApplicationConfig {
- configurationFile.SetConfigName(".app")
- configurationFile.AddConfigPath(configurationPath)
- err := configurationFile.MergeInConfig()
- if err != nil {
- log.Fatal(err)
- }
- }
-
- return configurationFile
-}
-
-type Artifact interface {
- exists() bool
- upload() bool
-}
-
-type DockerImageArtifact struct {
- idFile string
- repository string
- tag string
- usernameEnv string
- passwordEnv string
-}
-
-type HelmChartArtifact struct {
- chartPath string
- packageFilePath string
- packageFileName string
- repository string
- usernameEnv string
- passwordEnv string
- repositoryGitURL string
-}
-
-func getArtifactsConfiguration(configurationManager *viper.Viper) []interface{} {
- // if output defined in app config, skip all that were defined in root config
- // outputs should just be an array of artifacts
- // artifact should be an interface and each artifact type should define how to check for them
- artifacts := make([]interface{}, 2)
-
- dockerImage := DockerImageArtifact{
- idFile: configurationManager.GetString("Output.DockerImage.idFile"),
- repository: configurationManager.GetString("Output.DockerImage.repository"),
- tag: configurationManager.GetString("Output.DockerImage.tag"),
- usernameEnv: "KNEGA_DOCKER_USERNAME",
- passwordEnv: "KNEGA_DOCKER_PASSWORD",
- }
- artifacts[0] = dockerImage
-
- helmChart := HelmChartArtifact{
- chartPath: configurationManager.GetString("Output.HelmChart.chartPath"),
- packageFilePath: configurationManager.GetString("Output.HelmChart.packageFilePath"),
- packageFileName: configurationManager.GetString("Output.HelmChart.packageFileName"),
- repository: configurationManager.GetString("Output.HelmChart.repository"),
- usernameEnv: "KNEGA_HELM_USERNAME",
- passwordEnv: "KNEGA_HELM_PASSWORD",
- repositoryGitURL: configurationManager.GetString("Output.HelmChart.repositoryGitURL"),
- }
- artifacts[1] = helmChart
-
- return artifacts
-}
diff --git a/application.go b/application.go
deleted file mode 100644
index e4479b1..0000000
--- a/application.go
+++ /dev/null
@@ -1,232 +0,0 @@
-package main
-
-import (
- "path"
- "path/filepath"
- "log"
- "crypto/sha512"
- "encoding/hex"
- "strings"
- "os"
-)
-
-type ChangeStatus int
-
-const (
- Unknown ChangeStatus = iota
- Dirty
- Pristine
-)
-
-func (changeStatus ChangeStatus) String() string {
- return [...]string{"Unknown", "Dirty", "Pristine"}[changeStatus]
-}
-
-type Application struct {
- path string
- name string
- inputsHash string
- environment struct {
- name string
- urls []string
- variables []string
- }
- changeStatus ChangeStatus
- docker struct {
- idFile string
- repository string
- tag string
- username string
- password string
- }
- helm struct {
- chartPath string
- packageFilePath string
- packageFileName string
- repository string
- username string
- password string
- repositoryGitURL string
- }
- commands struct {
- check []string
- build []string
- analyze []string
- release []string
- }
- repository Repository
-}
-
-func initializeApplication(applicationPath string) Application {
- shouldInitializeApplications := false
- repository := initializeRepository(shouldInitializeApplications)
-
- applicationConfiguration := getApplicationConfiguration(applicationPath, repository)
-
- application := Application{
- name: applicationConfiguration.name,
- path: applicationPath,
- repository: repository,
- }
-
- inputPaths := resolveInputPaths(applicationConfiguration.inputs.filePaths, applicationConfiguration.inputs.gitFilePaths, application)
-
- applicationInputs := initializeBuildInputs(inputPaths)
- application.inputsHash = generateInputsHash(applicationInputs)
-
- application.docker.idFile = injectVariables(applicationConfiguration.outputs.dockerImage.idFile, application)
- application.docker.repository = injectVariables(applicationConfiguration.outputs.dockerImage.repository, application)
- application.docker.tag = injectVariables(applicationConfiguration.outputs.dockerImage.tag, application)
- dockerUsernameEnv := injectVariables(applicationConfiguration.outputs.dockerImage.usernameEnv, application)
- dockerPasswordEnv := injectVariables(applicationConfiguration.outputs.dockerImage.passwordEnv, application)
- application.docker.username = os.Getenv(dockerUsernameEnv)
- application.docker.password = os.Getenv(dockerPasswordEnv)
-
- application.helm.chartPath = injectVariables(applicationConfiguration.outputs.helmChart.chartPath, application)
- application.helm.packageFilePath = injectVariables(applicationConfiguration.outputs.helmChart.packageFilePath, application)
- application.helm.packageFileName = injectVariables(applicationConfiguration.outputs.helmChart.packageFileName, application)
- application.helm.repository = injectVariables(applicationConfiguration.outputs.helmChart.repository, application)
- application.helm.repositoryGitURL = injectVariables(applicationConfiguration.outputs.helmChart.repositoryGitURL, application)
- helmUsernameEnv := injectVariables(applicationConfiguration.outputs.helmChart.usernameEnv, application)
- helmPasswordEnv := injectVariables(applicationConfiguration.outputs.helmChart.passwordEnv, application)
- application.helm.username = os.Getenv(helmUsernameEnv)
- application.helm.password = os.Getenv(helmPasswordEnv)
-
- application.commands.check = injectVariablesArray(applicationConfiguration.commands.check, application)
- application.commands.build = injectVariablesArray(applicationConfiguration.commands.build, application)
- application.commands.analyze = injectVariablesArray(applicationConfiguration.commands.analyze, application)
- application.commands.release = injectVariablesArray(applicationConfiguration.commands.release, application)
-
- application.environment.name = applicationConfiguration.environment.name
- application.environment.urls = applicationConfiguration.environment.urls
-
- application.changeStatus = Unknown
-
- return application
-}
-
-func injectVariables(rawValue string, application Application) string {
- value := strings.Replace(rawValue, "$ROOT", application.repository.path, -1)
- value = strings.Replace(value, "$INPUTS_HASH", application.inputsHash, -1)
- value = strings.Replace(value, "$APPLICATION_NAME", application.name, -1)
-
- if fileExists(value) {
- value = filepath.Clean(value)
- }
-
- return value
-}
-
-func injectVariablesArray(rawValues []string, application Application) []string {
- var values []string
- for _, rawValue := range rawValues {
- value := injectVariables(rawValue, application)
- values = append(values, value)
- }
-
- return values
-}
-
-func resolveInputPaths(rawFilePaths []string, rawGitFilePaths []string, application Application) []string {
- filePaths := injectVariablesArray(rawFilePaths, application)
- gitFilePaths := injectVariablesArray(rawGitFilePaths, application)
-
- var rawInputPaths []string
- fileInputPaths := fileInputPatternsToPaths(filePaths, application.path)
- rawInputPaths = append(rawInputPaths, fileInputPaths...)
-
- gitFileInputPaths := gitFileInputPatternsToPaths(gitFilePaths, application.path)
- rawInputPaths = append(rawInputPaths, gitFileInputPaths...)
-
- inputPaths := deDuplicateStringSlice(rawInputPaths)
-
- return inputPaths
-}
-
-func fileInputPatternsToPaths(patterns []string, applicationPath string) []string {
- var results []string
-
- for _, pattern := range patterns {
- if !isAbsolutePath(pattern) {
- pattern = path.Join(applicationPath)
- }
- matches, err := filepath.Glob(pattern)
- if err != nil {
- log.Fatal(err)
- }
- results = append(results, matches...)
- }
- return results
-}
-
-func gitFileInputPatternsToPaths(patterns []string, applicationPath string) []string {
- var results []string
-
- for _, pattern := range patterns {
- matches := gitLsFiles(applicationPath, pattern)
- for _, relativePath := range matches {
- path := filepath.Join(applicationPath, relativePath)
- if fileExists(path) {
- results = append(results, path)
- }
- }
- }
-
- return results
-}
-
-func deDuplicateStringSlice(paths []string) []string {
- pathMap := make(map[string]string)
- var results []string
- for _, path := range paths {
- exists := pathMap[path]
- if exists == "" {
- pathMap[path] = path
- results = append(results, path)
- }
- }
-
- return results
-}
-
-func generateInputsHash (inputs []BuildInput) string {
- hash := sha512.New()
- for _, input := range inputs {
- hash.Write(input.Hash())
- }
- checksum := hash.Sum(nil)
-
- return hex.EncodeToString(checksum)
-}
-
-func (application *Application) hasChanges() bool {
- packageName := application.name
- packageVersion := "1.0.0-" + application.inputsHash
- hasHelmPackage := helmPackageExists(packageName, packageVersion, application)
-
- imageName := application.name
- imageTag := application.inputsHash
- hasDockerImage := dockerImageExists(imageName, imageTag, application)
-
- skipHelmPackage := application.helm.repository == ""
- skipDockerImage := application.docker.repository == ""
- hasArtifacts := ((skipHelmPackage || hasHelmPackage) && (skipDockerImage || hasDockerImage))
-
- if hasArtifacts {
- application.changeStatus = Pristine
- } else {
- application.changeStatus = Dirty
- }
-
- return !hasArtifacts
-}
-
-func (application *Application) hasTag(tag string) bool {
- // check if has tag
- return false
-}
-
-func (application *Application) nameContains(value string) bool {
- // check if name contains string
- return false
-}
diff --git a/build-input.go b/build-input.go
deleted file mode 100644
index b619bd4..0000000
--- a/build-input.go
+++ /dev/null
@@ -1,47 +0,0 @@
-package main
-
-import (
- "crypto/sha512"
- "os"
- "log"
- "io"
-)
-
-type BuildInput struct {
- path string
- // absolutePath string
- // rootRelativePath string
- // applicationRelativePath string
-}
-
-func initializeBuildInputs(paths []string) []BuildInput {
- var inputs []BuildInput
-
- for _, path := range paths {
- input := BuildInput{
- path: path,
- }
- inputs = append(inputs, input)
- }
-
- return inputs
-}
-
-func (buildInput *BuildInput) Hash() []byte {
- file, err := os.Open(buildInput.path)
- if err != nil {
- log.Fatal(err)
- }
-
- // close file on function return
- defer file.Close()
-
- hash := sha512.New()
-
- _, copyErr := io.Copy(hash, file)
- if copyErr != nil {
- log.Fatal(copyErr)
- }
-
- return hash.Sum(nil)
-}
diff --git a/build.go b/build.go
deleted file mode 100644
index 4947781..0000000
--- a/build.go
+++ /dev/null
@@ -1,44 +0,0 @@
-package main
-
-import (
- "os"
- "os/exec"
- "fmt"
-
- "github.com/urfave/cli"
-)
-
-func build(c *cli.Context) error {
- if fileExists("Dockerfile") {
- command := exec.Command("docker", "build", "-t", "app", "--iidfile", "container.id", ".")
- command.Stdout = os.Stdout
- command.Stderr = os.Stderr
- err := command.Run()
-
- if err != nil {
-
- return err
- }
- } else {
- workingDirectory, wdErr := os.Getwd()
- if wdErr != nil {
- fmt.Println(wdErr)
- }
- command := exec.Command(
- "docker", "run",
- "-e", "BUILDPACK_URL",
- "-v", workingDirectory + ":/tmp/app:ro",
- "gliderlabs/herokuish", "/bin/herokuish", "buildpack", "build",
- )
- command.Stdout = os.Stdout
- command.Stderr = os.Stderr
- err := command.Run()
-
- if err != nil {
-
- return err
- }
- }
-
- return nil
-}
diff --git a/changed.go b/changed.go
deleted file mode 100644
index 7e0683c..0000000
--- a/changed.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package main
-
-import (
- "sync"
- "log"
- "time"
-)
-
-func checkApplications(applications []Application) []Application {
- var checkedApplications []Application
- var asyncChangedChecks sync.WaitGroup
-
- checkedApplicationsChannel := make(chan Application, len(applications))
-
- log.Print("Checking if artifacts exist with those hashes")
-
- for _, application := range applications {
- asyncChangedChecks.Add(1)
- go func(checkedApplicationsChannel chan<- Application, application Application) {
- application.hasChanges()
- checkedApplicationsChannel<-application
- asyncChangedChecks.Done()
- }(checkedApplicationsChannel, application)
- }
- asyncChangedChecks.Wait()
- close(checkedApplicationsChannel)
- for checkedApplication := range checkedApplicationsChannel {
- checkedApplications = append(checkedApplications, checkedApplication)
- }
-
- return checkedApplications
-}
-
-func changed(action string) error {
- startTime := time.Now()
- repository := initializeRepository(true)
- var jobs []Job
-
- checkedApplications := checkApplications(repository.applications)
- printBuildStatus(checkedApplications)
- var changedApplications []Application
- for _, application := range checkedApplications {
- if application.changeStatus != Pristine {
- changedApplications = append(changedApplications, application)
- }
- }
-
- if len(changedApplications) > 0 {
- for _, application := range changedApplications {
- job := createJob(repository, application, action)
- jobs = append(jobs, job)
- }
-
- done := make(chan bool, 1)
- defer close(done)
-
- results := make(chan string, len(jobs))
-
- go pipelineResults(results, done, startTime, len(jobs), false)
- createWorkerPipeline(jobs, results)
-
- <-done
- }
-
- endTime := time.Now()
- timeTaken := endTime.Sub(startTime)
- log.Printf("Total time taken: %s", timeTaken)
-
- return nil
-}
diff --git a/code-quality.go b/code-quality.go
deleted file mode 100644
index aa243a7..0000000
--- a/code-quality.go
+++ /dev/null
@@ -1,29 +0,0 @@
-package main
-
-import (
- "path"
- "io/ioutil"
-)
-
-func codeQuality(application Application, repository Repository) error {
- reportPath := path.Join(repository.path, ".generated/code-quality")
- createIfNotExists(reportPath)
-
- scanCommand := "docker run --rm -v " + application.path + ":/code "
- scanCommand += "-v /var/run/docker.sock:/var/run/docker.sock "
- scanCommand += "-v /tmp/cc:/tmp/cc "
- scanCommand += "-v " + reportPath + ":/report "
- scanCommand += "-e CODECLIMATE_CODE=" + application.path + " "
- scanCommand += "codeclimate/codeclimate analyze -f html"
-
- result := executeCommandNoExtraLogs(scanCommand, application.repository.path)
-
- fileData := []byte(result)
- writeError := ioutil.WriteFile(reportPath + "/" + application.name + ".html", fileData, 0777)
-
- if writeError != nil {
- return writeError
- }
-
- return nil
-}
diff --git a/command.go b/command.go
deleted file mode 100644
index e02c7b4..0000000
--- a/command.go
+++ /dev/null
@@ -1,105 +0,0 @@
-package main
-
-import (
- "os/exec"
- "log"
- "strings"
- "bytes"
- "bufio"
-)
-
-func executeCommand(command string, directory string) string {
- commandParts := strings.Split(command, " ")
- commandExecutor := exec.Command(commandParts[0], commandParts[1:]...)
- commandExecutor.Dir = directory
-
- logReader, initErr := commandExecutor.StdoutPipe()
- if initErr != nil {
- log.Printf("Executing command: %s in %s, crashed before receiving any output", command, directory)
- log.Fatal(initErr)
- }
-
- commandExecutor.Stderr = commandExecutor.Stdout
-
- startError := commandExecutor.Start()
-
- if startError != nil {
- log.Printf("Executing command: %s in %s, crashed before receiving any output", command, directory)
- log.Fatal(startError)
- }
-
- var outputBuffer bytes.Buffer
-
- scanner := bufio.NewScanner(logReader)
-
- outputBuffer.Write([]byte("COMMAND: " + Info(command) + " in DIRECTORY: " + Info(directory)))
-
- for scanner.Scan() {
- outputBuffer.WriteRune('\n')
- outputBuffer.Write(scanner.Bytes())
- }
-
- if err := scanner.Err(); err != nil {
- commandExecutor.Wait()
- log.Print(string(outputBuffer.Bytes()))
- log.Fatal(err)
- }
-
- waitError := commandExecutor.Wait()
- if waitError != nil {
- log.Print(string(outputBuffer.Bytes()))
- log.Fatal(waitError)
- }
-
- return string(outputBuffer.Bytes())
-}
-
-func executeCommandNoExtraLogs(command string, directory string) string {
- commandParts := strings.Split(command, " ")
- commandExecutor := exec.Command(commandParts[0], commandParts[1:]...)
- commandExecutor.Dir = directory
-
- logReader, initErr := commandExecutor.StdoutPipe()
- if initErr != nil {
- log.Printf("Executing command: %s in %s, crashed before receiving any output", command, directory)
- log.Fatal(initErr)
- }
-
- commandExecutor.Stderr = commandExecutor.Stdout
-
- startError := commandExecutor.Start()
-
- if startError != nil {
- log.Printf("Executing command: %s in %s, crashed before receiving any output", command, directory)
- log.Fatal(startError)
- }
-
- var outputBuffer bytes.Buffer
-
- scanner := bufio.NewScanner(logReader)
- firstLine := true
-
- for scanner.Scan() {
- if firstLine {
- firstLine = false
- } else {
- outputBuffer.WriteRune('\n')
- }
-
- outputBuffer.Write(scanner.Bytes())
- }
-
- if err := scanner.Err(); err != nil {
- commandExecutor.Wait()
- log.Print(string(outputBuffer.Bytes()))
- log.Fatal(err)
- }
-
- waitError := commandExecutor.Wait()
- if waitError != nil {
- log.Print(string(outputBuffer.Bytes()))
- log.Fatal(waitError)
- }
-
- return string(outputBuffer.Bytes())
-}
diff --git a/create-chart.go b/create-chart.go
deleted file mode 100644
index 516e22d..0000000
--- a/create-chart.go
+++ /dev/null
@@ -1,130 +0,0 @@
-package main
-
-import (
- "os"
- "os/exec"
- "log"
-
- "github.com/urfave/cli"
- "github.com/otiai10/copy"
- "github.com/spf13/viper"
-)
-
-func createChart(cliContext *cli.Context, application Application, repository Repository) error {
- log.Printf("application-version: %s", cliContext.String("application-version"))
- // TODO: create ensureCleanDirectoryExists func in fs/path
- if directoryExists(".generated") {
- rmErr := os.RemoveAll(".generated")
- if rmErr != nil {
- log.Fatal(rmErr)
- }
- }
- os.Mkdir(".generated", 0777)
-
- chartPath := ".generated/default-app"
- // allow defining custom chart path in .knega.app.toml
- if directoryExists("chart") {
- copy.Copy("chart", chartPath)
- } else {
- // set directory in root .knega.root.toml
- baseChartPath := repository.baseChartPath
- if directoryExists(baseChartPath) {
- err := copy.Copy(baseChartPath, chartPath)
- if err != nil {
- log.Fatal(err)
- }
- } else {
- // generate default chart? download gitlab auto deploy chart?
- log.Fatal("To run create-chart you need to have either an application specific chart or a base chart defined")
- }
- }
-
- if fileExists("deploy-values.yml") {
- err := copy.Copy("deploy-values.yml", ".generated/deploy-values.yml")
- if err != nil {
- log.Fatal(err)
- }
- } else {
- os.Create(".generated/deploy-values.yml")
- }
-
- // load
- defaultValues := viper.New()
- defaultValues.SetConfigName("values")
- defaultValues.AddConfigPath("./.generated/default-app") // change to new chart name
- err := defaultValues.ReadInConfig()
- if err != nil {
- log.Fatal(err)
- }
-
- defaultValues.SetConfigName("deploy-values")
- defaultValues.AddConfigPath(".generated")
- err = defaultValues.MergeInConfig()
- if err != nil {
- log.Fatal(err)
- }
-
- defaultValues.SetConfigName("values")
- defaultValues.AddConfigPath("./.generated/default-app") // change to new chart name
-
- // TODO: not yet available, enable once merged (https://github.com/spf13/viper/pull/635)
- // what to do as a workaround until then?
- // lets try rewriting all files to lowercase for now, done at the end
- // defaultValues.SetKeysCaseSensitive(true)
-
- appConfig := viper.New()
- appConfig.SetConfigName(".app")
- appConfig.AddConfigPath(".")
- err = appConfig.ReadInConfig()
- if err != nil {
- log.Fatal(err)
- }
- applicationName := appConfig.GetString("name")
-
- defaultValues.Set("applicationName", applicationName)
-
- // TODO: should set chart name and .generated/ to applicationName-
- chart := viper.New()
- chart.SetConfigName("Chart")
- chart.AddConfigPath("./.generated/default-app") // change to new chart name
- err = chart.ReadInConfig()
- if err != nil {
- log.Fatal(err)
- }
- chart.Set("name", applicationName)
-
- inputsHash := application.inputsHash
- chartVersion := chart.GetString("version")
- if inputsHash != "" {
- chart.Set("appVersion", inputsHash)
- chart.Set("version", chartVersion + "-" + inputsHash)
- defaultValues.Set("image.tag", inputsHash)
- }
-
- defaultValues.WriteConfig()
- chart.WriteConfig()
-
- renameErr := os.Rename("./.generated/default-app", "./.generated/" + applicationName)
- if renameErr != nil {
- log.Fatal(renameErr)
- }
-
- // TODO: remove these once case sensitivity can be turned on for viper (1.5?)
- convertFileContentToLowerCase(".generated/" + applicationName + "/templates/_helpers.tpl")
- convertFileContentToLowerCase(".generated/" + applicationName + "/templates/deployment.yaml")
- convertFileContentToLowerCase(".generated/" + applicationName + "/templates/hpa.yaml")
- convertFileContentToLowerCase(".generated/" + applicationName + "/templates/ingress.yaml")
- convertFileContentToLowerCase(".generated/" + applicationName + "/templates/networkpolicy.yaml")
- convertFileContentToLowerCase(".generated/" + applicationName + "/templates/pdb.yaml")
- convertFileContentToLowerCase(".generated/" + applicationName + "/templates/service.yaml")
-
- command := exec.Command("helm", "package", "./.generated/" + applicationName, "--destination", ".generated")
- command.Stdout = os.Stdout
- command.Stderr = os.Stderr
- commandError := command.Run()
- if commandError != nil {
- log.Fatal(commandError)
- }
-
- return nil
-}
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000..9a85850
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,7 @@
+version: '3.3'
+
+services:
+ registry:
+ image: registry:latest
+ ports:
+ - 5000:5000
diff --git a/docker.go b/docker.go
deleted file mode 100644
index ab3b399..0000000
--- a/docker.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package main
-
-import (
- "log"
- "context"
- "encoding/json"
- "encoding/base64"
- "os"
-
- "github.com/urfave/cli"
- "docker.io/go-docker"
- "docker.io/go-docker/api/types"
-)
-
-func dockerUpload(cliContext *cli.Context, application Application) error {
- idFile := "container.id"
- containerId := readFile(idFile)
- username := application.docker.username
- password := application.docker.password
- dockerRepository := application.docker.repository
- tag := application.docker.tag
- fullTag := dockerRepository + ":" + tag
-
- log.Printf("----------------------------->ContainerID: %s", containerId)
-
- executeCommand("docker login -u " + username + " -p " + password + " " + dockerRepository, application.path)
- executeCommand("docker image tag " + containerId + " " + fullTag, application.path)
- executeCommand("docker push " + fullTag, application.path)
-
- return nil
-}
-
-func dockerImageExists(imageName string, imageTag string, application *Application) bool {
- context := context.Background()
- cli, err := docker.NewEnvClient()
- if err != nil {
- log.Fatal(err)
- }
-
- inspectAuthConfig := types.AuthConfig{
- Username: application.docker.username,
- Password: application.docker.password,
- }
- encodedJSON, err := json.Marshal(inspectAuthConfig)
- if err != nil {
- log.Fatal(err)
- }
- authStr := base64.URLEncoding.EncodeToString(encodedJSON)
-
- fullImagePath := application.docker.repository + ":" + imageTag
- _, inspectErr := cli.DistributionInspect(context, fullImagePath, authStr)
- if inspectErr != nil {
- log.Print(inspectErr)
- return false
- }
-
- return true
-}
-
-func dockerVulnerabilityScan(cliContext *cli.Context, application Application) error {
- idFile := "container.id"
- containerId := readFile(idFile)
- exitCode := cliContext.String("exit-code")
-
- generatedPath := application.repository.path + "/.generated"
- trivyCachePath := generatedPath + "/.trivy-cache"
- analyzePath := generatedPath + "/analyze"
- if !directoryExists(generatedPath) {
- os.Mkdir(generatedPath, 0777)
- }
- if !directoryExists(trivyCachePath) {
- os.Mkdir(trivyCachePath, 0777)
- }
- if !directoryExists(analyzePath) {
- os.Mkdir(analyzePath, 0777)
- }
- reportPath := analyzePath + "/" + application.name + ".json"
-
- executeCommand("trivy --cache-dir " + trivyCachePath + " --no-progress --exit-code 0 -f json -o " + reportPath + " " + containerId, application.path)
- executeCommand("trivy --cache-dir " + trivyCachePath + " --no-progress --exit-code " + exitCode + " " + containerId, application.path)
-
- return nil
-}
diff --git a/examples/.app.toml b/examples/.app.toml
deleted file mode 100644
index 638b6dd..0000000
--- a/examples/.app.toml
+++ /dev/null
@@ -1,4 +0,0 @@
-name = "my-application"
-
-# See defaults in .knega.root.toml
-# Any of those settings can be used here and will overwrite whatever was set in root
diff --git a/examples/.component.yml b/examples/.component.yml
new file mode 100644
index 0000000..c051e88
--- /dev/null
+++ b/examples/.component.yml
@@ -0,0 +1,15 @@
+name: "my-component"
+
+# See defaults in .knega.root.toml
+# Any of those settings can be used here and will overwrite whatever was set in root
+outputs:
+ # this component only has a chart output, override to get rid of default docker image
+- type: "OCI"
+ repository: "some-registry.com/charts/some-category/$COMPONENT_NAME"
+ # chart versions need to comply with semver, add 1.0.0 to pass validation
+ tag: "1.0.0-$INPUTS_HASH"
+
+actions:
+# do nothing on release
+- name: "release"
+ commands: []
diff --git a/examples/.knega.root.toml b/examples/.knega.root.toml
deleted file mode 100644
index 29b9ebb..0000000
--- a/examples/.knega.root.toml
+++ /dev/null
@@ -1,76 +0,0 @@
-# Currently relative to root directory, should be relative to application directory and allow overrides from appconfig
-# deploy-values.yml in application directory can be used to ovveride settings in values.yaml and included in the built chart
-# you can then use another config file or just --set for environment specific values when deploying
-baseChartPath = "shared/chart"
-
-# Defines where to look for applications
-applicationPaths = ["applications", "libraries", "infrastructure"]
-applicationSearchDepth = 2
-
-# Default configuration (used by applications, can be overwritten by app configuration)
-
-# Defines how to check for changes, a hash will be created based on the content of input files
-# input paths have $ROOT and $APPLICATION_NAME variable available and are relative to application directory
-[Input]
- [Input.Files]
- paths = ["$ROOT/.knega.root.toml"]
-
- [Input.GitFiles]
- # git ls-files (in application directory)
- paths = ["*"]
-# everything below has $ROOT, $INPUTS_HASH, $APPLICATION_NAME variables available
-[Output]
- [Output.DockerImage]
- # Path of idfile (docker build --iidfile), used by knega docker upload to find the correct image to upload
- idfile = "container.id"
- # Repository to check whether it was already built or to upload to
- repository = "some-registry.com/some-category/$APPLICATION_NAME"
- tag = "$INPUTS_HASH"
- # Which environment variables to grab username/password from
- # below are hardcoded for now
- # usernameEnv = "KNEGA_DOCKER_USERNAME"
- # passwordEnv = "KNEGA_DOCKER_PASSWORD"
-
- [Output.HelmChart]
- # uploading chart uses git and existence check uses helm search
- # to avoid conflicts this does not re-index the repository currently
- # i run knega chart update-index after build to avoid it happening in parallell
- packageFilePath = ".generated"
- packageFileName = "$APPLICATION_NAME-1.0.0-$INPUTS_HASH.tgz"
- repository = "https://raw.githubusercontent.com/user/repository/master"
- repositoryGitURL = "git@github.com:user/repository.git"
- # below are hardcoded for now
- # usernameEnv = "KNEGA_HELM_USERNAME"
- # passwordEnv = "KNEGA_HELM_PASSWORD"
-
-# All commands are run with application directory as working directory, root scripts can be run using $ROOT
-[Check]
- commands = [
- "knega test"
- ]
-
-[Build]
- commands = [
- "knega build",
- "knega chart create",
- "knega docker upload",
- "knega chart upload"
- ]
-
-# none of the analyze actions are implemented yet
-# [Analyze]
-# commands = [
-# "knega code-quality",
-# "knega dependency-vulnerability",
-# "knega container-vulnerability",
-# "knega performance",
-# "knega generate-report-bundle"
-# ]
-
-[Release]
- # knega release isn't implemented yet, so currently I'm running a bash script here like this
- # which also serves as an example of how knega tooling can be replaced for different parts
- commands = [
- "$ROOT/scripts/release.sh -a $APPLICATION_NAME -h $INPUTS_HASH"
- # "knega release"
- ]
diff --git a/examples/.knega.root.yml b/examples/.knega.root.yml
new file mode 100644
index 0000000..dadf24f
--- /dev/null
+++ b/examples/.knega.root.yml
@@ -0,0 +1,44 @@
+# Defines where to look for components
+componentPaths: ["services", "libraries"]
+
+# how many levels below component paths to search
+componentSearchDepth: 2
+
+# how many threads to run
+concurrency: 2
+
+# Default configuration for components, overriding a top level property is a replace
+defaultConfiguration:
+ # inputs define paths to files whose content will be summed into $INPUTS_HASH per component
+ inputs:
+ - type: "Files"
+ paths: ["$ROOT/.knega.root.yml"]
+ # git ls files *
+ - type: "GitFiles"
+ paths: ["*"]
+
+ # outputs define artifacts to check, if all artifacts the action can be skipped for that component with knega changed
+ outputs:
+ # Docker image example
+ - type: "OCI"
+ repository: "some-registry.com/some-category/$COMPONENT_NAME"
+ tag: "$INPUTS_HASH"
+ # Helm chart example
+ - type: "OCI"
+ repository: "some-registry.com/charts/some-category/$COMPONENT_NAME"
+ # chart version needs to comply with semver
+ tag: "1.0.0-$INPUTS_HASH"
+
+ # actions define collections of commands to be executed with knega changed/all
+ actions:
+ # name defines command name, ie knega changed build in this case
+ - name: "build"
+ # commands are executed with component directory as working directory, root scripts can be run using $ROOT
+ commands: [
+ "$ROOT/scripts/build.sh -a $COMPONENT_NAME -h $INPUTS_HASH"
+ ]
+ # example knega all release to execute these commands for all components
+ - name: "release"
+ commands: [
+ "$ROOT/scripts/release.sh -a $COMPONENT_NAME -h $INPUTS_HASH"
+ ]
diff --git a/examples/README.md b/examples/README.md
deleted file mode 100644
index de52108..0000000
--- a/examples/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-# Examples
-Examples are currently more of a design spec, thoughts on what I think a configuration should look like.
diff --git a/examples/full/.knega.root.yml b/examples/full/.knega.root.yml
new file mode 100644
index 0000000..f1ee2c4
--- /dev/null
+++ b/examples/full/.knega.root.yml
@@ -0,0 +1,23 @@
+componentPaths: ["components"]
+componentSearchDepth: 2
+concurrency: 2
+
+defaultConfiguration:
+ inputs:
+ - type: "Files"
+ paths: ["$ROOT/.knega.root.yml"]
+ - type: "GitFiles"
+ paths: ["*"]
+
+ outputs:
+ - type: "OCI"
+ repository: "localhost:5000/$COMPONENT_NAME"
+ tag: "$INPUTS_HASH"
+
+ actions:
+ - name: "build"
+ commands:
+ - 'echo "Component name: $COMPONENT_NAME"'
+ - 'echo "Root path: $ROOT"'
+ - 'echo "Inputs hash: $INPUTS_HASH"'
+ - $ROOT/scripts/build.sh
diff --git a/examples/full/components/example-1/.component.yml b/examples/full/components/example-1/.component.yml
new file mode 100644
index 0000000..560aa8b
--- /dev/null
+++ b/examples/full/components/example-1/.component.yml
@@ -0,0 +1 @@
+name: "example-1"
diff --git a/examples/full/components/example-1/Dockerfile b/examples/full/components/example-1/Dockerfile
new file mode 100644
index 0000000..67fd379
--- /dev/null
+++ b/examples/full/components/example-1/Dockerfile
@@ -0,0 +1 @@
+FROM alpine
diff --git a/examples/full/components/example-2/.component.yml b/examples/full/components/example-2/.component.yml
new file mode 100644
index 0000000..d187150
--- /dev/null
+++ b/examples/full/components/example-2/.component.yml
@@ -0,0 +1 @@
+name: "example-2"
diff --git a/examples/full/components/example-2/Dockerfile b/examples/full/components/example-2/Dockerfile
new file mode 100644
index 0000000..67fd379
--- /dev/null
+++ b/examples/full/components/example-2/Dockerfile
@@ -0,0 +1 @@
+FROM alpine
diff --git a/examples/full/components/test-only-1/.component.yml b/examples/full/components/test-only-1/.component.yml
new file mode 100644
index 0000000..2e7652f
--- /dev/null
+++ b/examples/full/components/test-only-1/.component.yml
@@ -0,0 +1,6 @@
+name: "test-only-1"
+
+actions:
+- name: "test"
+ commands:
+ - 'echo "test action executed in $COMPONENT_NAME"'
diff --git a/examples/full/scripts/build.sh b/examples/full/scripts/build.sh
new file mode 100755
index 0000000..c7de092
--- /dev/null
+++ b/examples/full/scripts/build.sh
@@ -0,0 +1,11 @@
+#! /bin/bash
+
+set -eux
+
+REGISTRY_URI=localhost:5000
+
+docker build \
+ -t $REGISTRY_URI/$COMPONENT_NAME:$INPUTS_HASH \
+ .
+
+docker push $REGISTRY_URI/$COMPONENT_NAME:$INPUTS_HASH
diff --git a/filterer.go b/filterer.go
deleted file mode 100644
index a070412..0000000
--- a/filterer.go
+++ /dev/null
@@ -1,66 +0,0 @@
-package main
-
-import (
- "github.com/urfave/cli"
-)
-
-type Filterer struct {
- tags []string
- applicationName string
-}
-
-func initializeFilterer(cliContext *cli.Context) Filterer {
- filterer := Filterer{
- applicationName: cliContext.String("application-name"),
- tags: cliContext.StringSlice("tags"),
- }
-
- return filterer
-}
-
-func filterApplications(applications []Application, test func(Application) bool) []Application {
- var result []Application
- for _, application := range applications {
- if test(application) {
- result = append(result, application)
- }
- }
- return result
-}
-
-func arrayAll(collection []string, test func(string) bool) bool {
- for _, collectionValue := range collection {
- if !test(collectionValue) {
- return false
- }
- }
- return true
-}
-
-func findIndex(collection []string, value string) int {
- for index, collectionValue := range collection {
- if collectionValue == value {
- return index
- }
- }
- return -1
-}
-
-func hasString(collection []string, value string) bool {
- return findIndex(collection, value) >= 0
-}
-
-func (filterer *Filterer) filter(applications []Application) []Application {
- hasTags := len(filterer.tags) > 0
- var result []Application
-
- if hasTags {
- hasTagsTest := func(application Application) bool {
- return arrayAll(filterer.tags, application.hasTag)
- }
-
- return filterApplications(applications, hasTagsTest)
- }
-
- return result
-}
diff --git a/fs.go b/fs.go
deleted file mode 100644
index fb87bb7..0000000
--- a/fs.go
+++ /dev/null
@@ -1,155 +0,0 @@
-package main
-
-import (
- "os"
- "log"
- "fmt"
- "path"
- "path/filepath"
- "io/ioutil"
- "bytes"
- "strings"
-)
-
-func fileExists(filename string) bool {
- info, err := os.Stat(filename)
- if os.IsNotExist(err) {
- return false
- }
-
- return !info.IsDir()
-}
-
-func directoryExists(directory string) bool {
- info, err := os.Stat(directory)
- if os.IsNotExist(err) {
- return false
- }
-
- return info.IsDir()
-}
-
-func directoriesExist(directories []string) {
- for _, directory := range directories {
- if ! directoryExists(directory) {
- log.Fatal("Directory does not exist", directory)
- }
- }
-}
-
-func getWorkingDirectory() string {
- workingDirectory, err := os.Getwd()
- if err != nil {
- log.Fatal(fmt.Errorf("Could not get working directory path", err))
- }
- return workingDirectory
-}
-
-func findSubDirectoriesWithFile(directory string, filename string, searchDepth int) []string {
- var results []string
- globPath := ""
-
- for depth := 0; depth <= searchDepth; depth++ {
- searchPath := path.Join(directory, globPath, filename)
- matches, err := filepath.Glob(searchPath)
- if err != nil {
- log.Fatal(err)
- }
- for _, match := range matches {
- absolutePath, err := filepath.Abs(match)
- if err != nil {
- log.Fatal(err)
- }
- absolutePath = strings.Replace(absolutePath, filename, "", 1)
- results = append(results, absolutePath)
- }
-
- globPath += "*/"
- }
-
- return results
-}
-
-func findParentDirectoryWithFile(directory string, filename string) string {
- searchDirectoryPath := directory
-
- // TODO: should stop search when at system root, for now just limit depth to 10
- for depth := 0; depth <= 10; depth++ {
- searchPath := path.Join(searchDirectoryPath, filename)
- if fileExists(searchPath) {
- absolutePath, err := filepath.Abs(searchPath)
- if err != nil {
- log.Fatal(err)
- }
-
- directoryPath := strings.Replace(absolutePath, filename, "", 1)
- // log.Print("Found root directory: " + directoryPath)
-
- return directoryPath
- }
- searchDirectoryPath += "../"
- }
- log.Fatal("Could not find parent directory with file")
-
- // never gets here, stops lint error complaint
- return ""
-}
-
-// TODO: implement this
-func isAbsolutePath(path string) bool {
- return true
-}
-
-// The horror.. need this until viper is fixed or replaced
-func convertFileContentToLowerCase(path string) {
- content, err := ioutil.ReadFile(path)
- if err != nil {
- log.Fatal(err)
- }
- lowerCaseContent := bytes.Replace(content, []byte(".applicationName"), []byte(".applicationname"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".replicaCount"), []byte(".replicacount"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".pullPolicy"), []byte(".pullpolicy"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".environmentVariables"), []byte(".environmentvariables"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte("ASPNETCORE_URLS"), []byte("aspnetcore_urls"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".internalPort"), []byte(".internalport"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".livenessProbe"), []byte(".livenessprobe"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".initialDelaySeconds"), []byte(".initialdelayseconds"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".timeoutSeconds"), []byte(".timeoutseconds"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".readinessProbe"), []byte(".readinessprobe"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".minReplicas"), []byte(".minreplicas"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".maxReplicas"), []byte(".maxreplicas"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".targetCPUUtilizationPercentage"), []byte("targetcpuutilizationpercentage"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".modSecurity"), []byte(".modsecurity"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".secRuleEngine"), []byte(".secruleengine"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".externalPort"), []byte(".externalport"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".podDisruptionBudget"), []byte(".poddisruptionbudget"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".minAvailable"), []byte(".minavailable"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".maxUnavailable"), []byte(".maxunavailable"), -1)
- lowerCaseContent = bytes.Replace(lowerCaseContent, []byte(".networkPolicy"), []byte(".networkpolicy"), -1)
-
- err = ioutil.WriteFile(path, lowerCaseContent, 0777)
-}
-
-func readFile(path string) string {
- output, err := ioutil.ReadFile(path)
- if err != nil {
- log.Fatal(err)
- }
- return string(output[:])
-}
-
-func clearDirectory(path string) {
- if directoryExists(path) {
- rmErr := os.RemoveAll(path)
- if rmErr != nil {
- log.Fatal(rmErr)
- }
- }
- os.Mkdir(path, 0777)
-}
-
-func createIfNotExists(path string) {
- if !directoryExists(path) {
- os.Mkdir(path, 0777)
- }
-}
diff --git a/git.go b/git.go
deleted file mode 100644
index e67ce65..0000000
--- a/git.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package main
-
-import (
- "strings"
- "os/exec"
- "log"
-)
-
-func gitCloneRepository(repositoryURL string, clonePath string, directory string) string {
- return executeCommand("git clone " + repositoryURL + " " + clonePath, directory)
-}
-
-func gitPull(directory string) string {
- output := executeCommand("git pull -r", directory)
-
- return output
-}
-
-func gitCommit(commitMessage string, directory string) string {
- output := executeCommand("git add -A", directory)
- output += executeCommand("git commit -m \"" + commitMessage + "\"", directory)
-
- return output
-}
-
-func gitPush(directory string) error {
- output := gitPull(directory)
- command := exec.Command("git", "push")
- command.Dir = directory
- result, err := command.Output()
-
- if err != nil {
- return err
- }
-
- output += string(result[:])
-
- log.Print(output)
-
- return nil
-}
-
-func gitLsFiles(directory string, pattern string) []string {
- output := executeCommand("git -c core.quotepath=off ls-files " + pattern, directory)
- relativePaths := strings.Split(output, "\n")
-
- return relativePaths
-}
diff --git a/go.mod b/go.mod
index b611ec4..2794b7a 100644
--- a/go.mod
+++ b/go.mod
@@ -1,20 +1,5 @@
-module knega
+module github.com/kristofferlind/knega
-go 1.13
+go 1.18
-require (
- docker.io/go-docker v1.0.0
- github.com/davecgh/go-spew v1.1.1
- github.com/docker/distribution v2.7.1+incompatible // indirect
- github.com/docker/docker v1.13.1
- github.com/docker/go-connections v0.4.0 // indirect
- github.com/docker/go-units v0.4.0 // indirect
- github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 // indirect
- github.com/opencontainers/go-digest v1.0.0-rc1 // indirect
- github.com/opencontainers/image-spec v1.0.1 // indirect
- github.com/otiai10/copy v1.0.2
- github.com/prune998/docker-registry-client v0.0.0-20190107194723-78de54b9f017
- github.com/spf13/viper v1.5.0
- github.com/urfave/cli v1.22.1
- golang.org/x/net v0.0.0-20190522155817-f3200d17e092
-)
+require gopkg.in/yaml.v3 v3.0.1
diff --git a/go.sum b/go.sum
index de8888a..a62c313 100644
--- a/go.sum
+++ b/go.sum
@@ -1,175 +1,4 @@
-cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
-docker.io/go-docker v1.0.0 h1:VdXS/aNYQxyA9wdLD5z8Q8Ro688/hG8HzKxYVEVbE6s=
-docker.io/go-docker v1.0.0/go.mod h1:7tiAn5a0LFmjbPDbyTPOaTTOuG1ZRNXdPA6RvKY+fpY=
-github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
-github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
-github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
-github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
-github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
-github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
-github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
-github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
-github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
-github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
-github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
-github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
-github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
-github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
-github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY=
-github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
-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/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
-github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
-github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug=
-github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
-github.com/docker/docker v1.13.1 h1:IkZjBSIc8hBjLpqeAbeE5mca5mNgeatLHBy3GO78BWo=
-github.com/docker/docker v1.13.1/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
-github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ=
-github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec=
-github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw=
-github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
-github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 h1:UhxFibDNY/bfvqU5CAUmr9zpesgbU6SWc8/B4mflAE4=
-github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7/go.mod h1:cyGadeNEkKy96OOhEzfZl+yxihPEzKnqJwvfuSUqbZE=
-github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
-github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
-github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
-github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
-github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
-github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
-github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
-github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
-github.com/gogo/protobuf v1.2.1 h1:/s5zKNz0uPFCZ5hddgPdo2TK2TVrUNMn0OOX8/aZMTE=
-github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
-github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
-github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
-github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
-github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
-github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
-github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
-github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
-github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
-github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
-github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
-github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
-github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
-github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
-github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
-github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
-github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
-github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
-github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
-github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
-github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
-github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
-github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
-github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=
-github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
-github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
-github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
-github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
-github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
-github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
-github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
-github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
-github.com/opencontainers/go-digest v1.0.0-rc1 h1:WzifXhOVOEOuFYOJAW6aQqW0TooG2iki3E3Ii+WN7gQ=
-github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s=
-github.com/opencontainers/image-spec v1.0.1 h1:JMemWkRwHx4Zj+fVxWoMCFm/8sYGGrUVojFA6h/TRcI=
-github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0=
-github.com/otiai10/copy v1.0.2 h1:DDNipYy6RkIkjMwy+AWzgKiNTyj2RUI9yEMeETEpVyc=
-github.com/otiai10/copy v1.0.2/go.mod h1:c7RpqBkwMom4bYTSkLSym4VSJz/XtncWRAj/J4PEIMY=
-github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE=
-github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo=
-github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
-github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
-github.com/pkg/errors v0.8.0 h1:WdK/asTD0HN+q6hsWO3/vpuAkAr+tw6aNJNDFFf0+qw=
-github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
-github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
-github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
-github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
-github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
-github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
-github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
-github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
-github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
-github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
-github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
-github.com/prune998/docker-registry-client v0.0.0-20190107194723-78de54b9f017 h1:tCm9TEwy6a1s3dboR9TZxQXHWrt1/+wTC65Jbcu65Uc=
-github.com/prune998/docker-registry-client v0.0.0-20190107194723-78de54b9f017/go.mod h1:0mv86yBh00jRSWDYBNe2Ev+RYZT/iVDWGeFS+B3gpMI=
-github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
-github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
-github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
-github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
-github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
-github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo=
-github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
-github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
-github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
-github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
-github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
-github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
-github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
-github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
-github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
-github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
-github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
-github.com/spf13/viper v1.4.0 h1:yXHLWeravcrgGyFSyCgdYpXQ9dR9c/WED3pg1RhxqEU=
-github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
-github.com/spf13/viper v1.5.0 h1:GpsTwfsQ27oS/Aha/6d1oD7tpKIqWnOA6tgOX9HHkt4=
-github.com/spf13/viper v1.5.0/go.mod h1:AkYRkVJF8TkSG/xet6PzXX+l39KhhXa2pdqVSxnTcn4=
-github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
-github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
-github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
-github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
-github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
-github.com/urfave/cli v1.22.1 h1:+mkCCcOFKPnCmVYVcURKps1Xe+3zP90gSYGNfRkjoIY=
-github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
-github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
-github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
-go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
-go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
-go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
-go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
-golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
-golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
-golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
-golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
-golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
-golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
-golang.org/x/net v0.0.0-20190522155817-f3200d17e092 h1:4QSRKanuywn15aTZvI/mIDEgPQpswuFndXpOj3rKEco=
-golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
-golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
-golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=
-golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
-golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
-golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
-golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
-golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
-golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
-golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
-google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
-google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
-google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
-google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
-gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
+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/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
-gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
-gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
-gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
-gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
-honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+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/helm.go b/helm.go
deleted file mode 100644
index 0eb1c29..0000000
--- a/helm.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package main
-
-import (
- "path"
- "os"
- "log"
- "strings"
- "regexp"
-
- "github.com/urfave/cli"
-)
-
-func createHelmRepositoryIndex(directory string) string {
- return executeCommand("helm repo index .", directory)
-}
-
-func updateHelmIndex(cliContext *cli.Context, repository Repository) error {
- generatedPath := path.Join(repository.path, ".generated")
- if ! directoryExists(generatedPath) {
- os.Mkdir(generatedPath, 0777)
- }
- repositoryName := "helm-repo"
- helmRepositoryPath := path.Join(repository.path, ".generated/", repositoryName)
- if ! directoryExists(helmRepositoryPath) {
- repositoryURL := repository.helm.repositoryGitURL
- log.Print(gitCloneRepository(repositoryURL, repositoryName, generatedPath))
- }
-
- commitMessage := "re-index"
- log.Print(createHelmRepositoryIndex(helmRepositoryPath))
- log.Print(gitCommit(commitMessage, helmRepositoryPath))
-
- // TODO: need a retry here.. probably for the clone aswell
- err := gitPush(helmRepositoryPath)
-
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func getLatestCommit(repository Repository) string {
- command := "git ls-remote " + repository.helm.repositoryGitURL + " refs/heads/master"
- commandResult := executeCommand(command, repository.path)
-
- expression, _ := regexp.Compile("([a-f0-9]{40})")
- commitId := expression.FindString(commandResult)
-
- return commitId
-}
-
-func setupHelmRepository(cliContext *cli.Context, repository Repository) error {
- commitId := getLatestCommit(repository)
- repositoryCommitUrl := strings.Replace(repository.helm.repository, "master", commitId, 1)
- addRepoCommand := "helm repo add --username " + repository.helm.username
- addRepoCommand += " --password " + repository.helm.password
- addRepoCommand += " knega-repo " + repositoryCommitUrl
- executeCommand(addRepoCommand, repository.path)
-
- executeCommand("helm repo update", repository.path)
-
- return nil
-}
-
-func helmPackageExists(packageName string, packageVersion string, application *Application) bool {
- // TODO: setupHelmRepository if knega-repo does not exist or just have it run once for first application it hits
- searchCommand := "helm search repo --version 1.0.0-" + application.inputsHash
- searchCommand += " knega-repo/" + application.name
- result := executeCommand(searchCommand, application.path)
-
- if strings.Contains(result, "No results found") {
- return false
- }
-
- if strings.Contains(result, "APP VERSION") {
- return true
- }
-
- log.Printf("Something went wrong while checking for helm chart search command: %s returned the following results: %s", searchCommand, result)
-
- return false
-}
diff --git a/internal/command/color.go b/internal/command/color.go
new file mode 100644
index 0000000..a94246b
--- /dev/null
+++ b/internal/command/color.go
@@ -0,0 +1,25 @@
+package command
+
+import "fmt"
+
+var (
+ Info = Teal
+ Success = Green
+ Warning = Yellow
+ Fatal = Red
+)
+
+var (
+ Red = Color("\033[1;31m%s\033[0m")
+ Yellow = Color("\033[1;33m%s\033[0m")
+ Green = Color("\033[1;32m%s\033[0m")
+ Teal = Color("\033[1;36m%s\033[0m")
+)
+
+func Color(colorString string) func(...interface{}) string {
+ sprint := func(args ...interface{}) string {
+ return fmt.Sprintf(colorString,
+ fmt.Sprint(args...))
+ }
+ return sprint
+}
diff --git a/internal/command/command.go b/internal/command/command.go
new file mode 100644
index 0000000..3cbcc2a
--- /dev/null
+++ b/internal/command/command.go
@@ -0,0 +1,73 @@
+package command
+
+import (
+ "bufio"
+ "bytes"
+ "fmt"
+ "log"
+ "os"
+ "os/exec"
+ "strings"
+)
+
+func ExecuteStopOnError(command string, directory string, variables map[string]string) string {
+ result, err := Execute(command, directory, variables)
+ if err != nil {
+ log.Print(result)
+ log.Fatal(err)
+ }
+ return result
+}
+
+func Execute(command string, directory string, variables map[string]string) (string, error) {
+ expandedCommand := command
+ environment := os.Environ()
+
+ for key, value := range variables {
+ commandKey := fmt.Sprintf("$%s", key)
+ expandedCommand = strings.ReplaceAll(expandedCommand, commandKey, value)
+ environment = append(environment, fmt.Sprintf("%s=%s", key, value))
+ }
+
+ commandParts := strings.Split(expandedCommand, " ")
+ commandExecutor := exec.Command(commandParts[0], commandParts[1:]...)
+
+ commandExecutor.Env = environment
+ commandExecutor.Dir = directory
+
+ logReader, initErr := commandExecutor.StdoutPipe()
+ if initErr != nil {
+ return fmt.Sprintf("Executing command: %s in %s, crashed before receiving any output", expandedCommand, directory), initErr
+ }
+
+ commandExecutor.Stderr = commandExecutor.Stdout
+
+ startError := commandExecutor.Start()
+
+ if startError != nil {
+ return fmt.Sprintf("Executing command: %s in %s, crashed before receiving any output", expandedCommand, directory), startError
+ }
+
+ var outputBuffer bytes.Buffer
+
+ scanner := bufio.NewScanner(logReader)
+
+ outputBuffer.Write([]byte("COMMAND: " + Info(expandedCommand) + " in DIRECTORY: " + Info(directory)))
+
+ for scanner.Scan() {
+ outputBuffer.WriteRune('\n')
+ outputBuffer.Write(scanner.Bytes())
+ }
+
+ if err := scanner.Err(); err != nil {
+ commandExecutor.Wait()
+ return outputBuffer.String(), err
+ }
+
+ waitError := commandExecutor.Wait()
+ if waitError != nil {
+ return outputBuffer.String(), waitError
+ }
+
+ return outputBuffer.String(), nil
+}
diff --git a/internal/configuration/action.go b/internal/configuration/action.go
new file mode 100644
index 0000000..a44c1d5
--- /dev/null
+++ b/internal/configuration/action.go
@@ -0,0 +1,17 @@
+package configuration
+
+type action struct {
+ Commands []string
+}
+
+func initializeActions(configurationActions []configurationAction) map[string]action {
+ actions := make(map[string]action)
+
+ for _, configurationAction := range configurationActions {
+ actions[configurationAction.Name] = action{
+ Commands: configurationAction.Commands,
+ }
+ }
+
+ return actions
+}
diff --git a/internal/configuration/component.go b/internal/configuration/component.go
new file mode 100644
index 0000000..89bd0e1
--- /dev/null
+++ b/internal/configuration/component.go
@@ -0,0 +1,89 @@
+package configuration
+
+import (
+ "crypto/sha512"
+ "encoding/hex"
+)
+
+type ChangeStatus int
+
+const (
+ Unknown ChangeStatus = iota
+ Dirty
+ Pristine
+)
+
+func (changeStatus ChangeStatus) String() string {
+ return [...]string{"Unknown", "Dirty", "Pristine"}[changeStatus]
+}
+
+type Component struct {
+ Path string
+ Name string
+ Inputs []input
+ Outputs []output
+ Actions map[string]action
+ InputsHash string
+ ChangeStatus ChangeStatus
+}
+
+func initializeComponent(componentPath string, rootConfiguration rootConfiguration, rootPath string) Component {
+ configuration := initializeComponentConfiguration(componentPath+"/.component.yml", rootConfiguration)
+
+ component := Component{
+ Path: componentPath,
+ Name: configuration.Name,
+ }
+
+ component.Inputs = initializeInputs(configuration.Inputs, componentPath, rootPath)
+ component.Outputs = initializeOutputs(configuration.Outputs)
+ component.Actions = initializeActions(configuration.Actions)
+ component.InputsHash = calculateHash(component.Inputs)
+ component.ChangeStatus = Unknown
+
+ return component
+}
+
+func initializeComponentConfiguration(componentConfigurationPath string, rootConfiguration rootConfiguration) componentConfiguration {
+ componentConfiguration := parseComponentConfiguration(componentConfigurationPath, rootConfiguration.DefaultConfiguration)
+
+ if componentConfiguration.Inputs == nil {
+ componentConfiguration.Inputs = rootConfiguration.DefaultConfiguration.Inputs
+ }
+ if componentConfiguration.Outputs == nil {
+ componentConfiguration.Outputs = rootConfiguration.DefaultConfiguration.Outputs
+ }
+ if componentConfiguration.Actions == nil {
+ componentConfiguration.Actions = rootConfiguration.DefaultConfiguration.Actions
+ }
+
+ return componentConfiguration
+}
+
+func (component *Component) HasChanges() bool {
+ hasChanges := false
+ component.ChangeStatus = Pristine
+ variables := map[string]string{
+ "COMPONENT_NAME": component.Name,
+ "INPUTS_HASH": component.InputsHash,
+ }
+ for _, output := range component.Outputs {
+ if !output.exists(variables) {
+ component.ChangeStatus = Dirty
+ hasChanges = true
+ }
+ }
+
+ return hasChanges
+}
+
+func calculateHash(inputs []input) string {
+ hash := sha512.New384()
+ for _, input := range inputs {
+ inputHash := input.Hash()
+ hash.Write(inputHash)
+ }
+ checksum := hash.Sum(nil)
+
+ return hex.EncodeToString(checksum)
+}
diff --git a/internal/configuration/configuration.go b/internal/configuration/configuration.go
new file mode 100644
index 0000000..2874eba
--- /dev/null
+++ b/internal/configuration/configuration.go
@@ -0,0 +1,66 @@
+package configuration
+
+import (
+ "io/ioutil"
+ "log"
+
+ "gopkg.in/yaml.v3"
+)
+
+type rootConfiguration struct {
+ ComponentPaths []string `yaml:"componentPaths"`
+ ComponentSearchDepth int `yaml:"componentSearchDepth"`
+ Concurrency int `yaml:"concurrency"`
+ DefaultConfiguration componentConfiguration `yaml:"defaultConfiguration"`
+}
+
+type configurationInput struct {
+ Type string `yaml:"type"`
+ Paths []string `yaml:"paths"`
+}
+
+type configurationOutput struct {
+ Type string `yaml:"type"`
+ Repository string `yaml:"repository"`
+ Tag string `yaml:"tag"`
+}
+
+type configurationAction struct {
+ Name string `yaml:"name"`
+ Commands []string `yaml:"commands"`
+}
+
+type componentConfiguration struct {
+ Name string `yaml:"name"`
+ Inputs []configurationInput `yaml:"inputs,omitempty"`
+ Outputs []configurationOutput `yaml:"outputs"`
+ Actions []configurationAction `yaml:"actions"`
+}
+
+func parseRootConfiguration(path string) rootConfiguration {
+ fileContent, err := ioutil.ReadFile(path)
+ if err != nil {
+ log.Fatalf("Error reading content of root config file: %v", err)
+ }
+ rootConfiguration := rootConfiguration{}
+ err = yaml.Unmarshal(fileContent, &rootConfiguration)
+ if err != nil {
+ log.Fatalf("Error parsing root config: %v", err)
+ }
+
+ return rootConfiguration
+}
+
+func parseComponentConfiguration(path string, defaultConfiguration componentConfiguration) componentConfiguration {
+ fileContent, err := ioutil.ReadFile(path)
+ if err != nil {
+ log.Fatalf("Error reading content of root config file: %v", err)
+ }
+ configuration := defaultConfiguration
+ err = yaml.Unmarshal(fileContent, &configuration)
+ if err != nil {
+ log.Fatalf("Error parsing root config: %v", err)
+ }
+
+ return configuration
+}
diff --git a/internal/configuration/fs.go b/internal/configuration/fs.go
new file mode 100644
index 0000000..99fa011
--- /dev/null
+++ b/internal/configuration/fs.go
@@ -0,0 +1,94 @@
+package configuration
+
+import (
+ "fmt"
+ "log"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+)
+
+func getWorkingDirectory() string {
+ workingDirectory, err := os.Getwd()
+ if err != nil {
+ log.Fatal(fmt.Errorf("could not get working directory path: %s", err))
+ }
+ return workingDirectory
+}
+
+func isFile(filename string) bool {
+ info, err := os.Stat(filename)
+ if os.IsNotExist(err) {
+ return false
+ }
+
+ return !info.IsDir()
+}
+
+func findRootDirectory(filename string) string {
+ searchDirectoryPath := getWorkingDirectory()
+
+ // TODO: should stop search when at system root, for now just limit depth to 10
+ for depth := 0; depth <= 10; depth++ {
+ searchPath := path.Join(searchDirectoryPath, filename)
+ if isFile(searchPath) {
+ absolutePath, err := filepath.Abs(searchPath)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ directoryPath := strings.Replace(absolutePath, filename, "", 1)
+
+ return directoryPath
+ }
+ searchDirectoryPath += "../"
+ }
+ log.Fatal("Could not find parent directory with file")
+
+ // never gets here, stops lint error complaint
+ return ""
+}
+
+func findComponents(directory string, filename string, searchDepth int) []string {
+ var results []string
+ globPath := ""
+
+ for depth := 0; depth <= searchDepth; depth++ {
+ searchPath := path.Join(directory, globPath, filename)
+ matches, err := filepath.Glob(searchPath)
+ if err != nil {
+ log.Fatal(err)
+ }
+ for _, match := range matches {
+ absolutePath, err := filepath.Abs(match)
+ if err != nil {
+ log.Fatal(err)
+ }
+ absolutePath = strings.Replace(absolutePath, filename, "", 1)
+ results = append(results, absolutePath)
+ }
+
+ globPath += "*/"
+ }
+
+ return results
+}
+
+func isDirectory(directory string) bool {
+ info, err := os.Stat(directory)
+ if os.IsNotExist(err) {
+ return false
+ }
+
+ return info.IsDir()
+}
+
+func areDirectories(directories []string) bool {
+ for _, directory := range directories {
+ if !isDirectory(directory) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/configuration/git.go b/internal/configuration/git.go
new file mode 100644
index 0000000..75ee139
--- /dev/null
+++ b/internal/configuration/git.go
@@ -0,0 +1,14 @@
+package configuration
+
+import (
+ "strings"
+
+ "github.com/kristofferlind/knega/internal/command"
+)
+
+func gitLsFiles(directory string, pattern string) []string {
+ output := command.ExecuteStopOnError("git -c core.quotepath=off ls-files "+pattern, directory, nil)
+ relativePaths := strings.Split(output, "\n")[1:]
+
+ return relativePaths
+}
diff --git a/internal/configuration/input.go b/internal/configuration/input.go
new file mode 100644
index 0000000..0cb0374
--- /dev/null
+++ b/internal/configuration/input.go
@@ -0,0 +1,106 @@
+package configuration
+
+import (
+ "crypto/sha512"
+ "io"
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+type input struct {
+ path string
+}
+
+func fileInputPatternsToPaths(patterns []string, rootPath string) []string {
+ var results []string
+
+ for _, pattern := range patterns {
+ pattern = strings.ReplaceAll(pattern, "$ROOT", rootPath)
+ matches, err := filepath.Glob(pattern)
+ if err != nil {
+ log.Fatal(err)
+ }
+ results = append(results, matches...)
+ }
+ return results
+}
+
+func gitFileInputPatternsToPaths(patterns []string, applicationPath string) []string {
+ var results []string
+
+ for _, pattern := range patterns {
+ matches := gitLsFiles(applicationPath, pattern)
+ for _, relativePath := range matches {
+ path := filepath.Join(applicationPath, relativePath)
+ if isFile(path) {
+ results = append(results, path)
+ }
+ }
+ }
+
+ return results
+}
+
+func deDuplicateStringSlice(paths []string) []string {
+ pathMap := make(map[string]string)
+ var results []string
+ for _, path := range paths {
+ exists := pathMap[path]
+ if exists == "" {
+ pathMap[path] = path
+ results = append(results, path)
+ }
+ }
+
+ return results
+}
+
+func initializeInputs(configurationInputs []configurationInput, componentPath string, rootPath string) []input {
+ var paths []string
+
+ for _, configurationInput := range configurationInputs {
+ switch configurationInput.Type {
+ case "Files":
+ filePaths := fileInputPatternsToPaths(configurationInput.Paths, rootPath)
+ paths = append(paths, filePaths...)
+ case "GitFiles":
+ filePaths := gitFileInputPatternsToPaths(configurationInput.Paths, componentPath)
+ paths = append(paths, filePaths...)
+ default:
+ log.Fatal("One of the input types does not have a handler, check types on handlers")
+ }
+ }
+
+ uniquePaths := deDuplicateStringSlice(paths)
+
+ var inputs []input
+
+ for _, path := range uniquePaths {
+ input := input{
+ path: path,
+ }
+ inputs = append(inputs, input)
+ }
+
+ return inputs
+}
+
+func (input *input) Hash() []byte {
+ file, err := os.Open(input.path)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ defer file.Close()
+
+ hash := sha512.New384()
+
+ _, copyErr := io.Copy(hash, file)
+ if copyErr != nil {
+ log.Fatal(copyErr)
+ }
+
+ return hash.Sum(nil)
+}
diff --git a/internal/configuration/output.go b/internal/configuration/output.go
new file mode 100644
index 0000000..688be2f
--- /dev/null
+++ b/internal/configuration/output.go
@@ -0,0 +1,47 @@
+package configuration
+
+import (
+ "log"
+ "os"
+ "strings"
+
+ "github.com/kristofferlind/knega/internal/command"
+)
+
+type output struct {
+ repository string
+ tag string
+}
+
+func initializeOutputs(configurationOutputs []configurationOutput) []output {
+ var outputs []output
+
+ for _, configurationOutput := range configurationOutputs {
+ output := output{
+ repository: configurationOutput.Repository,
+ tag: configurationOutput.Tag,
+ }
+ outputs = append(outputs, output)
+ }
+
+ return outputs
+}
+
+func (output *output) exists(variables map[string]string) bool {
+ repository := GetRepository()
+ registrySecurityArg := ""
+ allowInsecureRegistry := os.Getenv("KNEGA_ALLOW_INSECURE_REGISTRY")
+ if allowInsecureRegistry == "true" {
+ registrySecurityArg = " --insecure"
+ }
+
+ result, err := command.Execute("docker manifest inspect "+output.repository+":"+output.tag+registrySecurityArg, repository.RootPath, variables)
+
+ log.Print(result)
+
+ if err != nil {
+ return false
+ }
+
+ return !strings.Contains(result, "no such manifest")
+}
diff --git a/internal/configuration/repository.go b/internal/configuration/repository.go
new file mode 100644
index 0000000..f032a5e
--- /dev/null
+++ b/internal/configuration/repository.go
@@ -0,0 +1,78 @@
+package configuration
+
+import (
+ "log"
+ "sync"
+)
+
+type repository struct {
+ RootPath string
+ Concurrency int
+ components []Component
+ defaultConfiguration componentConfiguration
+}
+
+var lock = &sync.Mutex{}
+
+var instance *repository
+
+func GetRepository() *repository {
+ // first instance check to avoid lock mechanism on every retrieval
+ if instance == nil {
+ lock.Lock()
+ defer lock.Unlock()
+
+ // check instance again as first check was before lock
+ if instance == nil {
+ instance = initialize()
+ }
+ }
+
+ return instance
+}
+
+func initialize() *repository {
+ fileName := ".knega.root.yml"
+ rootPath := findRootDirectory(fileName)
+ configuration := parseRootConfiguration(rootPath + fileName)
+
+ if !areDirectories(configuration.ComponentPaths) {
+ log.Fatal("One of your component paths is not an existing directory")
+ }
+
+ components := getComponents(configuration, rootPath)
+
+ repository := repository{
+ RootPath: rootPath,
+ Concurrency: configuration.Concurrency,
+ components: components,
+ defaultConfiguration: configuration.DefaultConfiguration,
+ }
+
+ return &repository
+}
+
+func getComponents(configuration rootConfiguration, rootPath string) []Component {
+ var results []Component
+ for _, searchFolder := range configuration.ComponentPaths {
+ componentConfigPaths := findComponents(searchFolder, ".component.yml", configuration.ComponentSearchDepth)
+ for _, componentConfigPath := range componentConfigPaths {
+ component := initializeComponent(componentConfigPath, configuration, rootPath)
+ results = append(results, component)
+ }
+ }
+
+ return results
+}
+
+func (repository *repository) FindComponentsWithAction(action string) []Component {
+ var components []Component
+ for _, component := range repository.components {
+ _, hasProperty := component.Actions[action]
+ if hasProperty {
+ components = append(components, component)
+ }
+ }
+
+ return components
+}
diff --git a/internal/orchestrator/job.go b/internal/orchestrator/job.go
new file mode 100644
index 0000000..3280b5d
--- /dev/null
+++ b/internal/orchestrator/job.go
@@ -0,0 +1,9 @@
+package orchestrator
+
+type job struct {
+ componentName string
+ action string
+ commands []string
+ workingDirectory string
+ variables map[string]string
+}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
new file mode 100644
index 0000000..4c85c78
--- /dev/null
+++ b/internal/orchestrator/orchestrator.go
@@ -0,0 +1,94 @@
+package orchestrator
+
+import (
+ "log"
+ "os"
+ "sync"
+ "time"
+
+ "github.com/kristofferlind/knega/internal/configuration"
+)
+
+func Execute(action string, skipExisting bool) error {
+ startTime := time.Now()
+ repository := configuration.GetRepository()
+ components := repository.FindComponentsWithAction(action)
+
+ var componentsToExecute []configuration.Component
+ if skipExisting {
+ componentsToExecute = getComponentsWithChanges(components)
+ } else {
+ componentsToExecute = components
+ }
+
+ var jobs []job
+ for _, component := range componentsToExecute {
+ job := job{
+ componentName: component.Name,
+ action: action,
+ commands: component.Actions[action].Commands,
+ workingDirectory: component.Path,
+ variables: map[string]string{
+ "ROOT": repository.RootPath,
+ "COMPONENT_NAME": component.Name,
+ "INPUTS_HASH": component.InputsHash,
+ },
+ }
+
+ jobs = append(jobs, job)
+ }
+
+ if len(jobs) > 0 {
+ createPipeline(jobs)
+ }
+
+ endTime := time.Now()
+ executionTime := endTime.Sub(startTime)
+ log.Printf("Total time taken: %s", executionTime)
+
+ return nil
+}
+
+func getComponentsWithChanges(components []configuration.Component) []configuration.Component {
+ var asyncChangedChecks sync.WaitGroup
+ var checkedComponents []configuration.Component
+ var changedComponents []configuration.Component
+
+ checkedComponentsChannel := make(chan configuration.Component, len(components))
+
+ for _, component := range components {
+ asyncChangedChecks.Add(1)
+
+ go func(changedComponentsChannel chan<- configuration.Component, component configuration.Component) {
+ component.HasChanges()
+ changedComponentsChannel <- component
+ asyncChangedChecks.Done()
+ }(checkedComponentsChannel, component)
+ }
+
+ asyncChangedChecks.Wait()
+ close(checkedComponentsChannel)
+
+ for checkedComponent := range checkedComponentsChannel {
+ checkedComponents = append(checkedComponents, checkedComponent)
+ if checkedComponent.ChangeStatus != configuration.Pristine {
+ changedComponents = append(changedComponents, checkedComponent)
+ }
+ }
+
+ printStatus(checkedComponents)
+
+ return changedComponents
+}
+
+func getMin(a int, b int) int {
+ if a <= b {
+ return a
+ }
+ return b
+}
+
+func IsTrace() bool {
+ traceValue := os.Getenv("KNEGA_TRACE")
+ return traceValue == "true"
+}
diff --git a/internal/orchestrator/pipeline.go b/internal/orchestrator/pipeline.go
new file mode 100644
index 0000000..dd263ab
--- /dev/null
+++ b/internal/orchestrator/pipeline.go
@@ -0,0 +1,52 @@
+package orchestrator
+
+import (
+ "log"
+ "sync"
+ "time"
+
+ "github.com/kristofferlind/knega/internal/command"
+ "github.com/kristofferlind/knega/internal/configuration"
+)
+
+func createPipeline(jobs []job) {
+ jobsCount := len(jobs)
+ repository := configuration.GetRepository()
+ threads := getMin(repository.Concurrency, jobsCount)
+
+ log.Printf("Created %v jobs and %v workers", jobsCount, threads)
+
+ queue := make(chan job, jobsCount)
+ for _, job := range jobs {
+ queue <- job
+ }
+
+ close(queue)
+
+ var asyncWorkers sync.WaitGroup
+
+ for workerId := 1; workerId <= threads; workerId++ {
+ asyncWorkers.Add(1)
+ go createWorker(&asyncWorkers, queue)
+ }
+
+ asyncWorkers.Wait()
+}
+
+func createWorker(asyncWorkers *sync.WaitGroup, jobs <-chan job) {
+ for job := range jobs {
+ jobStartTime := time.Now()
+
+ for _, jobCommand := range job.commands {
+ output := command.ExecuteStopOnError(jobCommand, job.workingDirectory, job.variables)
+ if IsTrace() {
+ log.Printf("%s", output)
+ }
+ }
+
+ jobEndTime := time.Now()
+ jobTime := jobEndTime.Sub(jobStartTime)
+ log.Printf("%s completed in %s", job.componentName, jobTime)
+ }
+ asyncWorkers.Done()
+}
diff --git a/internal/orchestrator/status.go b/internal/orchestrator/status.go
new file mode 100644
index 0000000..5f8c961
--- /dev/null
+++ b/internal/orchestrator/status.go
@@ -0,0 +1,30 @@
+package orchestrator
+
+import (
+ "fmt"
+ "os"
+ "sort"
+ "text/tabwriter"
+
+ "github.com/kristofferlind/knega/internal/command"
+ "github.com/kristofferlind/knega/internal/configuration"
+)
+
+func printStatus(components []configuration.Component) {
+ sort.Slice(components, func(i, j int) bool {
+ return components[i].Name < components[j].Name
+ })
+ writer := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.StripEscape)
+ for _, component := range components {
+ if component.ChangeStatus == configuration.Unknown {
+ fmt.Fprintf(writer, "%s: \t "+command.Warning("Unknown")+"\t %s\n", component.Name, component.InputsHash[0:19])
+ }
+ if component.ChangeStatus == configuration.Dirty {
+ fmt.Fprintf(writer, "%s: \t "+command.Fatal("Rebuild required")+"\t %s\n", component.Name, component.InputsHash[0:19])
+ }
+ if component.ChangeStatus == configuration.Pristine {
+ fmt.Fprintf(writer, "%s: \t "+command.Success("Artifacts found")+"\t %s\n", component.Name, component.InputsHash[0:19])
+ }
+ }
+ writer.Flush()
+}
diff --git a/job.go b/job.go
deleted file mode 100644
index 5eb687f..0000000
--- a/job.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package main
-
-import (
- "log"
-)
-
-type Job struct {
- application Application
- action string
- commands []string
- workingDirectory string
-}
-
-func createJob(repository Repository, application Application, action string) Job {
- var commands []string
- switch action {
- case "check":
- commands = application.commands.check
- case "build":
- commands = application.commands.build
- case "analyze":
- commands = application.commands.analyze
- case "release":
- commands = application.commands.release
- default:
- log.Fatal("Action is not available")
- }
-
- job := Job{
- action: action,
- application: application,
- commands: commands,
- workingDirectory: application.path,
- }
-
- return job
-}
diff --git a/logger.go b/logger.go
deleted file mode 100644
index a90c543..0000000
--- a/logger.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package main
-
-/*
-
-create logger with loglevels (debug, verbose, minimal)
-default: minimal
--v toggles verbose
--vv (very verbose) toggles debug
-
-*/
diff --git a/main.go b/main.go
index 0493a6c..92e7bab 100644
--- a/main.go
+++ b/main.go
@@ -1,274 +1,29 @@
package main
import (
- "log"
- "os"
- "path"
+ "log"
+ "os"
- "github.com/urfave/cli"
+ "github.com/kristofferlind/knega/internal/orchestrator"
)
func main() {
- app := cli.NewApp()
- app.Name = "Knega"
- app.Usage = "A collection of tasks for analyzing, testing, building and deploying your application"
-
- // if currentDirectory has appconfig, initialize repository without applications
- // and initialize just the application for current directory
- // might also be a reasonable alternative to reverse the relationship between repository and applications, most actions focus on application rather than repository
- // so have applications hold a reference to repository rather than the other way around
- // then single application commands should get single application and all commands should get an array of applications
- // for now just get from repository
-
- /*
- TODO: if currentDirectory has appconfig, initializeApplication
- if rootConfig is found initialize repository at application.repository
- */
-
- app.Commands = []cli.Command{
- {
- Name: "code-quality",
- Usage: "knega code-quality, uses codeclimate to analyze code quality and generate html report",
- Action: func(cliContext *cli.Context) error {
- repository := initializeRepository(false)
- var application Application
- currentWorkingDirectory := getWorkingDirectory()
-
- if (path.Clean(currentWorkingDirectory) != path.Clean(repository.path)) {
- application = initializeApplication(currentWorkingDirectory)
- }
-
- return codeQuality(application, repository)
- },
- },
- {
- Name: "build",
- Usage: "Builds application (uses dockerfile if it exists, otherwise tries herokuish)",
- Action: build,
- },
- {
- Name: "test",
- Usage: "Test application (using herokuish)",
- Category: "Analyze",
- Action: test,
- },
- {
- Name: "release",
- Usage: "Deploy",
- Action: func(cliContext *cli.Context) error {
- repository := initializeRepository(false)
- var application Application
- currentWorkingDirectory := getWorkingDirectory()
-
- if (path.Clean(currentWorkingDirectory) != path.Clean(repository.path)) {
- application = initializeApplication(currentWorkingDirectory)
- }
-
- return release(cliContext, application)
- },
- },
- {
- Name: "chart",
- Usage: "chart handles chart actions like create and upload",
- Subcommands: []cli.Command{
- {
- Name: "create",
- Usage: "knega chart create, creates chart based on app configuration",
- Action: func(cliContext *cli.Context) error {
- repository := initializeRepository(false)
- var application Application
- currentWorkingDirectory := getWorkingDirectory()
-
- if (path.Clean(currentWorkingDirectory) != path.Clean(repository.path)) {
- application = initializeApplication(currentWorkingDirectory)
- }
-
- return createChart(cliContext, application, repository)
- },
- },
- {
- Name: "upload",
- Usage: "knega chart upload, uploads chart to helm repository (only works for git based repositories currently)",
- Action: func(cliContext *cli.Context) error {
- repository := initializeRepository(false)
- var application Application
- currentWorkingDirectory := getWorkingDirectory()
-
- if (path.Clean(currentWorkingDirectory) != path.Clean(repository.path)) {
- application = initializeApplication(currentWorkingDirectory)
- }
-
- return uploadChart(cliContext, application)
- },
- },
- {
- Name: "setup-repository",
- Usage: "knega chart setup-repository, needed for helm exist check to work (done seperately because it's slow)",
- Action: func(cliContext *cli.Context) error {
- repository := initializeRepository(false)
-
- return setupHelmRepository(cliContext, repository)
- },
- },
- {
- Name: "update-index",
- Usage: "knega chart update-index, updates repository index (done seperately to avoid conflicts while pushing",
- Action: func(cliContext *cli.Context) error {
- repository := initializeRepository(false)
-
- return updateHelmIndex(cliContext, repository)
- },
- },
- },
- },
- {
- Name: "docker",
- Usage: "docker handles docker actions like create and upload",
- Subcommands: []cli.Command{
- {
- Name: "create",
- Usage: "Builds application (uses dockerfile if it exists, otherwise tries herokuish)",
- Action: build,
- },
- {
- Name: "upload",
- Usage: "knega docker upload, tags and uploads docker image to repository",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "docker-username",
- Value: "",
- Usage: "Username used by docker login",
- EnvVar: "KNEGA_DOCKER_USERNAME",
- },
- cli.StringFlag{
- Name: "docker-password",
- Value: "",
- Usage: "Password used by docker login",
- EnvVar: "KNEGA_DOCKER_PASSWORD",
- },
- },
- Action: func(cliContext *cli.Context) error {
- repository := initializeRepository(false)
- var application Application
- currentWorkingDirectory := getWorkingDirectory()
-
- if (path.Clean(currentWorkingDirectory) != path.Clean(repository.path)) {
- application = initializeApplication(currentWorkingDirectory)
- }
-
- return dockerUpload(cliContext, application)
- },
- },
- {
- Name: "vulnerability-scan",
- Usage: "knega docker vulnerability-scan, scans docker image for known vulnerabilities (trivy)",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "exit-code",
- Value: "1",
- Usage: "Set exit-code for vulnerabilities found",
- },
- },
- Action: func(cliContext *cli.Context) error {
- repository := initializeRepository(false)
- var application Application
- currentWorkingDirectory := getWorkingDirectory()
-
- if (path.Clean(currentWorkingDirectory) != path.Clean(repository.path)) {
- application = initializeApplication(currentWorkingDirectory)
- }
-
- return dockerVulnerabilityScan(cliContext, application)
- },
- },
- },
- },
- {
- Name: "all",
- Usage: "all will run action for all applications",
- Subcommands: []cli.Command{
- {
- Name: "check",
- Usage: "Run build command defined in application configs where changes have occurred",
- Action: func(c *cli.Context) error {
- return all("check")
- },
- },
- {
- Name: "build",
- Usage: "Run build command defined in application configs where changes have occurred",
- Action: func(context *cli.Context) error {
- return all("build")
- },
- },
- {
- Name: "analyze",
- Usage: "Run analyze command defined in application configs where changes have occurred",
- Action: func(context *cli.Context) error {
- return all("analyze")
- },
- },
- {
- Name: "release",
- Usage: "Run release command in all applications, passing in $INPUTS_HASH",
- Action: func(context *cli.Context) error {
- return all("release")
- },
- },
- },
- },
- {
- Name: "changed",
- Usage: "changed will run action for all applications with changes",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "docker-username",
- Value: "",
- Usage: "Username used by docker login",
- EnvVar: "KNEGA_DOCKER_USERNAME",
- },
- cli.StringFlag{
- Name: "docker-password",
- Value: "",
- Usage: "Password used by docker login",
- EnvVar: "KNEGA_DOCKER_PASSWORD",
- },
- },
- Subcommands: []cli.Command{
- {
- Name: "check",
- Usage: "Run build command defined in application configs where changes have occurred",
- Action: func(c *cli.Context) error {
- return changed("check")
- },
- },
- {
- Name: "build",
- Usage: "Run build command defined in application configs where changes have occurred",
- Action: func(context *cli.Context) error {
- return changed("build")
- },
- },
- {
- Name: "analyze",
- Usage: "Run analyze command defined in application configs where changes have occurred",
- Action: func(context *cli.Context) error {
- return changed("analyze")
- },
- },
- {
- Name: "release",
- Usage: "Run release command in all applications, passing in $INPUTS_HASH",
- Action: func(context *cli.Context) error {
- return changed("release")
- },
- },
- },
- },
- }
-
- err := app.Run(os.Args)
- if err != nil {
- log.Fatal(err)
- }
+ var skipExisting bool
+ if len(os.Args) < 2 {
+ log.Print("Usage: knega changed/all , where action is one of the defined actions in your configuration")
+ os.Exit(2)
+ }
+ switch os.Args[1] {
+ case "changed":
+ skipExisting = true
+ case "all":
+ skipExisting = false
+ default:
+ log.Print("Usage: knega changed/all , where action is one of the defined actions in your configuration")
+ os.Exit(2)
+ }
+
+ action := os.Args[2]
+
+ orchestrator.Execute(action, skipExisting)
}
diff --git a/release.go b/release.go
deleted file mode 100644
index a4b7924..0000000
--- a/release.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package main
-
-import (
- "path"
- "strings"
-
- "github.com/urfave/cli"
-)
-
-func release(cliContext *cli.Context, application Application) error {
- fetchPath := path.Join(application.repository.path, ".generated/charts")
- renderPath := path.Join(application.repository.path, ".generated/rendered_charts")
- createIfNotExists(fetchPath)
- createIfNotExists(renderPath)
-
- commitId := getLatestCommit(application.repository)
- repositoryCommitUrl := strings.Replace(application.helm.repository, "master", commitId, 1)
-
- fetchCommand := "helm fetch --repo " + repositoryCommitUrl
- fetchCommand += " --username " + application.helm.username
- fetchCommand += " --password " + application.helm.password
- fetchCommand += " --untar --untardir " + fetchPath
- fetchCommand += " --version 1.0.0-" + application.inputsHash
- fetchCommand += " --debug " + application.name
- executeCommand(fetchCommand, application.repository.path)
-
- renderCommand := "helm template --set environment=" + application.environment.name
- if len(application.environment.urls) > 0 {
- renderCommand += ",ingress.enabled=true,ingress.urls={" + strings.Join(application.environment.urls[:], ",") + "}"
- }
-
- // if len(application.environment.variables) > 0 {
- // renderCommand += ",configMapRefs.environmentVariables=" + application.name + "-environment-variables-secret"
- /*
- set application.secretName like in auto-deploy-app (https://gitlab.com/gitlab-org/charts/auto-deploy-app)
- generate configmap like this, with an environment variable for each line:
-apiVersion: v1
-kind: ConfigMap
-metadata:
- name: special-config
- namespace: default
-data:
- SPECIAL_LEVEL: very
- SPECIAL_TYPE: charm
-
-chart should grab variables from secret if set:
-apiVersion: v1
-kind: Pod
-metadata:
- name: dapi-test-pod
-spec:
- containers:
- - name: test-container
- image: k8s.gcr.io/busybox
- command: [ "/bin/sh", "-c", "env" ]
- envFrom:
- - configMapRef:
- name: special-config
- restartPolicy: Never
- */
- // for _, environmentVariable := range application.environment.variables {
- //
- // }
- // }
- renderCommand += " --output-dir " + renderPath
- renderCommand += " " + fetchPath + "/" + application.name
- executeCommand(renderCommand, application.repository.path)
-
- // should only happen once, doing it outside of knega for now
- // releaseCommand := "kubectl apply --recursive --filename " + renderPath
- // executeCommand(releaseCommand, application.repository.path)
-
- return nil
-}
diff --git a/repository.go b/repository.go
deleted file mode 100644
index 42ca8ef..0000000
--- a/repository.go
+++ /dev/null
@@ -1,71 +0,0 @@
-package main
-
-import (
- "log"
- "fmt"
- "os"
-
- "github.com/spf13/viper"
-)
-
-type Repository struct {
- path string
- searchDirectories []string
- searchDepth int
- applications []Application
- baseChartPath string
- helm struct{
- username string
- password string
- repository string
- repositoryGitURL string
- }
-}
-
-func initializeRepository(shouldIncludeApplications bool) Repository {
- workingDirectory := getWorkingDirectory()
- repositoryPath := findParentDirectoryWithFile(workingDirectory, ".knega.root.toml")
-
- viper.SetConfigName(".knega.root")
- viper.AddConfigPath(repositoryPath)
- err := viper.ReadInConfig()
- if err != nil {
- log.Fatal(fmt.Errorf("Fatal error config file: %s \n", err))
- }
-
- repository := Repository{
- path: repositoryPath,
- baseChartPath: repositoryPath + viper.GetString("baseChartPath"),
- searchDirectories: viper.GetStringSlice("applicationPaths"),
- searchDepth: viper.GetInt("applicationSearchDepth"),
- }
-
- // TODO: do update as part of chart upload instead, make it a job that runs for one of the applications once all workers are done
- repository.helm.repositoryGitURL = viper.GetString("Output.HelmChart.repositoryGitURL")
- repository.helm.repository = viper.GetString("Output.HelmChart.repository")
- repository.helm.username = os.Getenv("KNEGA_HELM_USERNAME")
- repository.helm.password = os.Getenv("KNEGA_HELM_PASSWORD")
-
- if shouldIncludeApplications {
- directoriesExist(repository.searchDirectories)
- repository.applications = getApplications(repository)
- }
-
- // log.Printf("Initialized repository %s", repository.path)
-
- return repository
-}
-
-func getApplications(repository Repository) []Application {
- var results []Application
- log.Print("Generating hashes of applications..")
- for _, searchFolder := range repository.searchDirectories {
- applicationConfigPaths := findSubDirectoriesWithFile(searchFolder, ".app.toml", repository.searchDepth)
- for _, applicationConfigPath := range applicationConfigPaths {
- application := initializeApplication(applicationConfigPath)
- results = append(results, application)
- // log.Printf("%s: %s", application.name, application.inputsHash)
- }
- }
- return results
-}
diff --git a/retry.go b/retry.go
deleted file mode 100644
index 888459b..0000000
--- a/retry.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package main
-
-import (
- "math/rand"
- "time"
-)
-
-func init() {
- rand.Seed(time.Now().UnixNano())
-}
-
-func retry(attempts int, sleep time.Duration, f func() error) error {
- if err := f(); err != nil {
- if s, ok := err.(stop); ok {
- // Return the original error for later checking
- return s.error
- }
-
- if attempts--; attempts > 0 {
- // Add some randomness to prevent creating a Thundering Herd
- jitter := time.Duration(rand.Int63n(int64(sleep)))
- sleep = sleep + jitter/2
-
- time.Sleep(sleep)
- return retry(attempts, 2*sleep, f)
- }
- return err
- }
-
- return nil
-}
-
-type stop struct {
- error
-}
diff --git a/shell.nix b/shell.nix
new file mode 100644
index 0000000..a24773b
--- /dev/null
+++ b/shell.nix
@@ -0,0 +1,12 @@
+# archive reference is nixpkgs-unstable from 2022-11-01
+{ pkgs ? import (fetchTarball "https://github.com/NixOS/nixpkgs/archive/e6e6bad81b7e11f37d893ef39712ce8918ae2338.tar.gz") {} }:
+
+pkgs.mkShell {
+ buildInputs = [
+ pkgs.bats
+ pkgs.docker
+ pkgs.docker-compose
+ pkgs.git
+ pkgs.go
+ ];
+}
diff --git a/status.go b/status.go
deleted file mode 100644
index 6e222f1..0000000
--- a/status.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package main
-
-import (
- "fmt"
- "os"
- "text/tabwriter"
-)
-
-var (
- Info = Teal
- Success = Green
- Warning = Yellow
- Fatal = Red
-)
-
-var (
- Red = Color("\033[1;31m%s\033[0m")
- Yellow = Color("\033[1;33m%s\033[0m")
- Green = Color("\033[1;32m%s\033[0m")
- Teal = Color("\033[1;36m%s\033[0m")
-)
-
-func Color(colorString string) func(...interface{}) string {
- sprint := func(args ...interface{}) string {
- return fmt.Sprintf(colorString,
- fmt.Sprint(args...))
- }
- return sprint
-}
-
-func printBuildStatus(applications []Application) {
- writer := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.StripEscape)
- for _, application := range applications {
- if application.changeStatus == Unknown {
- fmt.Fprintf(writer, "%s: \t " + Warning("Unknown") + "\t %s\n", application.name, application.inputsHash[0:19])
- }
- if application.changeStatus == Dirty {
- fmt.Fprintf(writer, "%s: \t " + Fatal("Rebuild required") + "\t %s\n", application.name, application.inputsHash[0:19])
- }
- if application.changeStatus == Pristine {
- fmt.Fprintf(writer, "%s: \t " + Success("Artifacts found") + "\t %s\n", application.name, application.inputsHash[0:19])
- }
- }
- writer.Flush()
-}
diff --git a/test.go b/test.go
deleted file mode 100644
index 4e5b777..0000000
--- a/test.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package main
-
-import (
- "os"
- "os/exec"
- "fmt"
-
- "github.com/urfave/cli"
-)
-
-func test(c *cli.Context) error {
- workingDirectory, wdErr := os.Getwd()
- if wdErr != nil {
- fmt.Println(wdErr)
- }
- command := exec.Command(
- "docker", "run",
- "-e", "BUILDPACK_URL",
- "-v", workingDirectory + ":/tmp/app:ro",
- "gliderlabs/herokuish", "/bin/herokuish", "buildpack", "test",
- )
- command.Stdout = os.Stdout
- command.Stderr = os.Stderr
- err := command.Run()
-
- if err != nil {
-
- return err
- }
-
- return nil
-}
diff --git a/test/build.bats b/test/build.bats
new file mode 100644
index 0000000..ba5a68a
--- /dev/null
+++ b/test/build.bats
@@ -0,0 +1,24 @@
+#!/usr/bin/env bats
+
+@test "knega without arguments should display usage" {
+ run $KNEGA
+ [ "$status" -eq 2 ]
+ [[ "$output" = *"Usage: knega changed"* ]]
+}
+
+@test "knega changed build should build everything when starting from scratch" {
+ run $KNEGA changed build
+ [[ "$output" = *"example-1"*"Rebuild required"* ]]
+ [[ "$output" = *"example-2"*"Rebuild required"* ]]
+}
+
+@test "knega changed build should build nothing on second run" {
+ run $KNEGA changed build
+ [[ "$output" = *"example-1"*"Artifacts found"* ]]
+ [[ "$output" = *"example-2"*"Artifacts found"* ]]
+}
+
+@test "knega all build should build everything even if artifacts already exist" {
+ run $KNEGA all build
+ [[ "$output" = *"Created 2 jobs"* ]]
+}
diff --git a/test/setup_suite.bash b/test/setup_suite.bash
new file mode 100644
index 0000000..1c1e853
--- /dev/null
+++ b/test/setup_suite.bash
@@ -0,0 +1,7 @@
+setup_suite() {
+ KNEGA=${KNEGA:-knega}
+ CURRENT_DIRECTORY=$(pwd)
+ SCRIPT_DIRECTORY="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+ CONFIGURATION_DIRECTORY=$SCRIPT_DIRECTORY/../examples/full
+ cd $CONFIGURATION_DIRECTORY
+}
diff --git a/test/test.bats b/test/test.bats
new file mode 100644
index 0000000..fbadac5
--- /dev/null
+++ b/test/test.bats
@@ -0,0 +1,7 @@
+#!/usr/bin/env bats
+
+@test "knega changed test should only execute where action test defined" {
+ run $KNEGA changed test
+ [[ "$output" = *"test action executed in test-only-1"* ]]
+ [[ "$output" != *"example-1"* ]]
+}
diff --git a/upload-chart.go b/upload-chart.go
deleted file mode 100644
index c9aa406..0000000
--- a/upload-chart.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package main
-
-import (
- "path"
- "os"
- "log"
- "io"
- "time"
-
- "github.com/urfave/cli"
-)
-
-func uploadChart(context *cli.Context, application Application) error {
- generatedPath := path.Join(application.repository.path, ".generated")
- if ! directoryExists(generatedPath) {
- os.Mkdir(generatedPath, 0777)
- }
-
- // do one repository per application to minimze conflicts
- repositoryName := application.name + "-repo"
- helmRepositoryPath := path.Join(application.repository.path, ".generated/", repositoryName)
- if ! directoryExists(helmRepositoryPath) {
- repositoryURL := application.helm.repositoryGitURL
- log.Print(gitCloneRepository(repositoryURL, repositoryName, generatedPath))
- }
- packageFileName := application.helm.packageFileName
- packagePath := path.Join(application.helm.packageFilePath, packageFileName)
-
- packageDestinationDirectory := path.Join(helmRepositoryPath, "charts")
- if ! directoryExists(packageDestinationDirectory) {
- os.Mkdir(packageDestinationDirectory, 0777)
- }
-
- packageDestinationPath := path.Join(packageDestinationDirectory, packageFileName)
- log.Print(packageDestinationPath)
-
- sourceFile, sourceErr := os.Open(packagePath)
- if sourceErr != nil {
- return sourceErr
- }
- defer sourceFile.Close()
-
- destinationFile, destinationErr := os.Create(packageDestinationPath)
- if destinationErr != nil {
- return destinationErr
- }
- defer destinationFile.Close()
-
- _, copyErr := io.Copy(destinationFile, sourceFile)
- if copyErr != nil {
- return copyErr
- }
-
- // do helm repository reindex after build instead to avoid conflicts
- // log.Print(createHelmRepositoryIndex(helmRepositoryPath))
- commitMessage := application.name + "-" + application.inputsHash
- log.Print(gitCommit(commitMessage, helmRepositoryPath))
-
- retry(10, time.Second, func() error {
- err := gitPush(helmRepositoryPath)
- if err != nil {
- return err
- }
- return nil
- })
-
- return nil
-}
diff --git a/utility.go b/utility.go
deleted file mode 100644
index a7a5a01..0000000
--- a/utility.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package main
-
-import (
- "os"
-)
-
-func getMin(a int, b int) int {
- if a <= b {
- return a
- }
- return b
-}
-
-func IsTrace() bool {
- traceValue := os.Getenv("KNEGA_TRACE")
- if traceValue == "true" {
- return true
- }
-
- return false
-}