Skip to content

Commit

Permalink
Merge branch 'main' into tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kehiy authored Jul 24, 2024
2 parents 49ffdd1 + 43dcd1b commit 1fca553
Show file tree
Hide file tree
Showing 57 changed files with 2,325 additions and 1,489 deletions.
51 changes: 51 additions & 0 deletions .github/workflows/semantic-pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ on:
- opened
- edited
- synchronize
- reopened

permissions:
pull-requests: read

jobs:
main:
Expand All @@ -15,3 +19,50 @@ jobs:
- uses: amannn/action-semantic-pull-request@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
# Configure which scopes are allowed (newline-delimited).
scopes: |
github
linter
deps
makefile
release
other
daemon
cmd
gtk
shell
wallet-cmd
committee
config
consensus
crypto
docs
execution
genesis
network
node
sandbox
scripts
sortition
state
store
sync
main
txpool
types
util
version
wallet
grpc
http
jsonrpc
nanomsg
# Configure that a scope must always be provided.
requireScope: true
# The subject should not start with an uppercase character and should not end with a period.
subjectPattern: ^(?![A-Z]).+[^.]$
subjectPatternError: |
The subject "{subject}" cannot start with an uppercase character or end with a period.
88 changes: 58 additions & 30 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,36 @@
# Contributing

Thank you for considering contributing to Pactus blockchain!
Thank you for considering contributing to the Pactus blockchain!
Please read these guidelines before submitting a pull request or opening an issue.

## Code Guidelines

We strive to maintain clean, readable, and maintainable code in Pactus blockchain.
Please follow these guidelines when contributing code to the project:
We strive to maintain clean, readable, and maintainable code in the Pactus blockchain.
Please follow these guidelines when contributing to the project:

- Code should follow the [Effective Go](https://golang.org/doc/effective_go.html) guidelines.
- Documentation should follow the [Go Doc Comments](https://go.dev/doc/comment) format.
- Follow the principles of clean code as outlined in Robert C. Martin's "[Clean Code](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882)" book. Here you can find a [summary](https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29) of the book.
- Follow the [Effective Go](https://golang.org/doc/effective_go.html) guidelines.
- Follow the [Go Doc Comments](https://go.dev/doc/comment) guidelines.
- Follow the principles of clean code as outlined in
Robert C. Martin's "[Clean Code](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882)" book.
- Write tests for new code or changes to existing code, and make sure all tests pass before submitting a pull request.
- Error strings and log messages should not be capitalized (unless beginning with proper nouns or acronyms) and
SHOULD NOT end with punctuation. Examples:
* Correct ✅: "unable to connect to server"
* Incorrect ❌: "Unable to connect to server"
* Incorrect ❌: "unable to connect to server."

The following commands are available in the Makefile:
### Makefile Targets

You can use these commands in the Makefile:

- `make build` compiles the code into executable binaries.
- `make devtools` installs required development tools.
- `make fmt` formats the code according to the Go standards.
- `make check` runs various checks on the code, including formatting and linting.
- `make test` performs all the tests including unit tests and system tests.
- `make uint_test` performs only unit tests.
- `make proto` generates [protobuf](https://protobuf.dev/) files, if you have made any changes to the proto buffer files.
- `make check` runs checks on the code, including formatting and linting.
- `make test` runs all the tests, including unit tests and system tests.
- `make unit_test` runs only unit tests.
- `make proto` generates [protobuf](https://protobuf.dev/) files.
Run this target if you have made any changes to the proto buffer files.

### Error and Log Messages

Error and log messages should not start with a capital letter (unless it's a proper noun or acronym) and
should not end with punctuation.

All changes on core must contain proper and well-defined unit-tests, also previous tests must be passed as well.
This codebase used `testify` for unit tests, make sure you follow these guide for tests:
Expand All @@ -38,24 +42,31 @@ This codebase used `testify` for unit tests, make sure you follow these guide fo

> This code guideline must be followed for both contributors and maintainers to review the PRs.
## CLI Guidelines
#### Examples

The help messages for CLI flags should follow this pattern:
- Correct ✅: "unable to connect to server"
- Incorrect ❌: "Unable to connect to server"
- Incorrect ❌: "unable to connect to server."

- Start all messages with a lowercase letter.
- Avoid stating defaults in the help string, as Cobra automatically adds them.
- Include a range for flags that accept a range of values.
### Help Messages

Follow these rules for help messages for CLI commands and flags:

- Help string should not start with a capital letter.
- Help string should not end with punctuation.
- Don't include default value in the help string.
- Include the acceptable range for the flags that accept a range of values.

## Commit Guidelines

Please follow these guidelines when committing changes to Pactus blockchain:
Please follow these rules when committing changes to the Pactus blockchain:

- Each commit should represent a single, atomic change to the codebase.
Avoid making multiple unrelated changes in a single commit.
- Commit message should not be longer than 50 characters.
- Commit message should start with lowercase and not ends with punctuation.
- Write commit message in the imperative: "fix bug" and not "fixed bug" or "fixes bug".
- Use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) format for commit messages and Pull Request titles.
- Use the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) format for commit messages and
Pull Request titles.

### Commit type

List of conventional commit [types](https://github.com/commitizen/conventional-commit-types/blob/master/index.json):

Expand All @@ -72,16 +83,33 @@ List of conventional commit [types](https://github.com/commitizen/conventional-c
| style | Changes that do not affect the meaning of the code (white-space, formatting, etc) |
| chore | Other changes that don't modify src or test files |

### Example fo commit messages
### Commit Scope

The scope helps specify which part of the code is affected by your commit.
It must be included in the commit message to provide clarity.
Multiple scopes can be used if the changes impact several areas.

Here’s a list of available scopes: [available scopes](./.github/workflows/semantic-pr.yml).

### Commit Description

- Keep the commit message under 50 characters.
- Start the commit message with a lowercase letter and do not end with punctuation.
- Write commit messages in the imperative: "fix bug" not "fixed bug" or "fixes bug".

### Examples

- Correct ✅: "feat(gRPC): sign transaction using wallet client"
- Correct ✅: "feat(grpc): sign transaction using wallet client"
- Correct ✅: "feat(grpc, wallet): sign transaction using wallet client"
- Incorrect ❌: 'feat(gRPC): Sign transaction using wallet client."
- Incorrect ❌: 'feat(gRPC): signed transaction using wallet client"
- Incorrect ❌: 'feat(grpc): Sign transaction using wallet client."
- Incorrect ❌: 'feat(grpc): signed transaction using wallet client"
- Incorrect ❌: 'sign transaction using wallet client"

## Code of Conduct

This project has adapted the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/)
This project has adapted the
[Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/)
to ensure that our community is welcoming and inclusive for all.
Please read it before contributing to the project.

Expand Down
6 changes: 3 additions & 3 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -634,18 +634,18 @@ func MakeValidatorKey(walletInstance *wallet.Wallet, valAddrsInfo []vault.Addres
return valKeys, nil
}

func TerminalProgressBar(totalSize, barWidth int, showBytes bool) *progressbar.ProgressBar {
func TerminalProgressBar(totalSize int64, barWidth int) *progressbar.ProgressBar {
if barWidth < 15 {
barWidth = 15
}

opts := []progressbar.Option{
progressbar.OptionSetWriter(ansi.NewAnsiStdout()),
progressbar.OptionEnableColorCodes(true),
progressbar.OptionShowBytes(showBytes),
progressbar.OptionSetWidth(barWidth),
progressbar.OptionSetElapsedTime(false),
progressbar.OptionSetPredictTime(false),
progressbar.OptionShowDescriptionAtLineEnd(),
progressbar.OptionSetTheme(progressbar.Theme{
Saucer: "[green]=[reset]",
SaucerHead: "[green]>[reset]",
Expand All @@ -655,5 +655,5 @@ func TerminalProgressBar(totalSize, barWidth int, showBytes bool) *progressbar.P
}),
}

return progressbar.NewOptions(totalSize, opts...)
return progressbar.NewOptions64(totalSize, opts...)
}
87 changes: 31 additions & 56 deletions cmd/daemon/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@ import (
"fmt"
"os"
"path/filepath"
"time"

"github.com/gofrs/flock"
"github.com/pactus-project/pactus/cmd"
"github.com/pactus-project/pactus/genesis"
"github.com/pactus-project/pactus/util"
"github.com/spf13/cobra"
)
Expand All @@ -21,7 +19,7 @@ func buildImportCmd(parentCmd *cobra.Command) {
parentCmd.AddCommand(importCmd)

workingDirOpt := addWorkingDirOption(importCmd)
serverAddrOpt := importCmd.Flags().String("server-addr", "https://download.pactus.org",
serverAddrOpt := importCmd.Flags().String("server-addr", cmd.DefaultSnapshotURL,
"import server address")

importCmd.Run = func(c *cobra.Command, _ []string) {
Expand All @@ -46,39 +44,25 @@ func buildImportCmd(parentCmd *cobra.Command) {
return
}

storeDir, _ := filepath.Abs(conf.Store.StorePath())
if !util.IsDirNotExistsOrEmpty(storeDir) {
cmd.PrintErrorMsgf("The data directory is not empty: %s", conf.Store.StorePath())

return
}
cmd.PrintLine()

snapshotURL := *serverAddrOpt
importer, err := cmd.NewImporter(
gen.ChainType(),
snapshotURL,
conf.Store.DataPath(),
)
cmd.FatalErrorCheck(err)

switch gen.ChainType() {
case genesis.Mainnet:
snapshotURL += "/mainnet/"
case genesis.Testnet:
snapshotURL += "/testnet/"
case genesis.Localnet:
cmd.PrintErrorMsgf("Unsupported chain type: %s", gen.ChainType())

return
}

metadata, err := cmd.GetSnapshotMetadata(c.Context(), snapshotURL)
if err != nil {
cmd.PrintErrorMsgf("Failed to get snapshot metadata: %s", err)

return
}
metadata, err := importer.GetMetadata(c.Context())
cmd.FatalErrorCheck(err)

snapshots := make([]string, 0, len(metadata))

for _, m := range metadata {
item := fmt.Sprintf("snapshot %s (%s)",
parseTime(m.CreatedAt).Format("2006-01-02"),
util.FormatBytesToHumanReadable(m.TotalSize),
m.CreatedAtTime().Format("2006-01-02"),
util.FormatBytesToHumanReadable(m.Data.Size),
)

snapshots = append(snapshots, item)
Expand All @@ -89,34 +73,32 @@ func buildImportCmd(parentCmd *cobra.Command) {
choice := cmd.PromptSelect("Please select a snapshot", snapshots)

selected := metadata[choice]
tmpDir := util.TempDirPath()
extractPath := fmt.Sprintf("%s/data", tmpDir)

err = os.MkdirAll(extractPath, 0o750)
cmd.FatalErrorCheck(err)
cmd.TrapSignal(func() {
_ = fileLock.Unlock()
_ = importer.Cleanup()
})

cmd.PrintLine()

zipFileList := cmd.DownloadManager(
importer.Download(
c.Context(),
&selected,
snapshotURL,
tmpDir,
downloadProgressBar,
)

for _, zFile := range zipFileList {
err := cmd.ExtractAndStoreFile(zFile, extractPath)
cmd.FatalErrorCheck(err)
}
cmd.PrintLine()
cmd.PrintLine()
cmd.PrintInfoMsgf("Extracting files...")

err = os.MkdirAll(filepath.Dir(conf.Store.StorePath()), 0o750)
err = importer.ExtractAndStoreFiles()
cmd.FatalErrorCheck(err)

err = cmd.CopyAllFiles(extractPath, conf.Store.StorePath())
cmd.PrintInfoMsgf("Moving data...")
err = importer.MoveStore()
cmd.FatalErrorCheck(err)

err = os.RemoveAll(tmpDir)
err = importer.Cleanup()
cmd.FatalErrorCheck(err)

_ = fileLock.Unlock()
Expand All @@ -131,19 +113,12 @@ func buildImportCmd(parentCmd *cobra.Command) {
}

func downloadProgressBar(fileName string, totalSize, downloaded int64, _ float64) {
bar := cmd.TerminalProgressBar(int(totalSize), 30, true)
bar.Describe(fileName)
err := bar.Add(int(downloaded))
bar := cmd.TerminalProgressBar(totalSize, 30)
bar.Describe(fmt.Sprintf("%s (%s/%s)",
fileName,
util.FormatBytesToHumanReadable(uint64(downloaded)),
util.FormatBytesToHumanReadable(uint64(totalSize)),
))
err := bar.Add64(downloaded)
cmd.FatalErrorCheck(err)
}

func parseTime(dateString string) time.Time {
const layout = "2006-01-02T15:04:05.000000"

parsedTime, err := time.Parse(layout, dateString)
if err != nil {
return time.Time{}
}

return parsedTime
}
2 changes: 2 additions & 0 deletions cmd/daemon/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,11 @@ func buildInitCmd(parentCmd *cobra.Command) {

return
}

var mnemonic string
if *restoreOpt == "" {
mnemonic, _ = wallet.GenerateMnemonic(*entropyOpt)

cmd.PrintLine()
cmd.PrintInfoMsgf("Your wallet seed is:")
cmd.PrintInfoMsgBoldf(" " + mnemonic)
Expand Down
Loading

0 comments on commit 1fca553

Please sign in to comment.