Skip to content

Commit 88e21e9

Browse files
authored
REFAC: complete overhaul of code structure
- commands infrastructure - commands refine - fmt-to-log - rename communication to websocket - websocket Client & Socket - clogger custom logging - watcher rewrite
2 parents bea983e + fb8cd05 commit 88e21e9

75 files changed

Lines changed: 4052 additions & 1233 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

CONVENTIONS.md

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
# Code Conventions
2+
3+
These arent strict rules, just a description of how the code is generally written so you know what to expect when reading through it or contributing.
4+
5+
## Type prefixes
6+
7+
Theres a loose system of prefixes that tell you what kind of type youre looking at:
8+
9+
| Prefix | Kind | Examples |
10+
|:-------|:-----|:---------|
11+
| `S` | Struct | `SClient`, `SSocket`, `SRequest` |
12+
| `M` | Map | `MFileState`, `MLogLevel` |
13+
| `T` | Defined type / alias | `TLogLevel`, `TMethod` |
14+
| `E` | Enum / bitmask | `EFileEvent`, `ELogLevel` |
15+
| `Fn` | Function type | `FnValidator`, `FnExecution` |
16+
17+
That said, not every type follows this. Some packages just dont use prefixes at all.
18+
19+
## Pointer vs value receivers
20+
21+
Pointer receiver if the method mutates anything or if the type holds a mutex or a channel. Value receiver otherwise:
22+
```go
23+
func (this *MFileState) Push(path string) error // pointer: mutates
24+
func (this SClog) Clone(override SClog) SClog // value: returns a copy
25+
func (this TList) String() string // value: read-only
26+
```
27+
28+
## Variable declarations
29+
30+
Avoid creating single character variables and instead make the variable name descriptive for its use.
31+
The exception to this is of course some universal conventions like `i`, `j`, `k` ... in for loops.
32+
33+
Use `var` over `:=`.
34+
It is generally harder to spot a single `:` to find the point of decleration.
35+
The keyword `var` is usually also colored differently which makes spotting it even easier.
36+
```go
37+
var str strings.Builder
38+
var info, err = os.Stat(path)
39+
```
40+
`:=` only really shows up in `for range` loops and `if`-scoped declarations:
41+
```go
42+
for i, arg := range args { }
43+
if idx := strings.LastIndex(partial, "/"); idx >= 0 { }
44+
```
45+
46+
## Receiver name
47+
48+
Always use `this`.
49+
There is no reason (currently known to me) not to use `this` as the receiver.
50+
```go
51+
func (this *SClient) Active() bool { return this.Connection != nil }
52+
```
53+
The benefits:
54+
- You dont have to think of another good and descriptive variable name.
55+
- You never have to question what the receiver is for this function.
56+
57+
58+
## Error handling
59+
60+
Check the error right after the call, no `fmt.Errorf` wrapping, no `defer`-error patterns. Just the straightforward `if err != nil` and log it.
61+
62+
## Logging
63+
64+
Every package that logs makes its own logger:
65+
66+
```go
67+
var clog = clogger.Default.Clone(clogger.SClog{Name: "packagename"})
68+
```
69+
70+
Each level has a regular and a formatted variant, so you get both `Error(msg)` and `Errorf(format, args...)` and the same goes for the rest.
71+
72+
## String building
73+
74+
`strings.Builder` for anything more than a one-liner:
75+
```go
76+
var builder strings.Builder
77+
builder.WriteString(alias)
78+
builder.WriteRune('\n')
79+
return builder.String()
80+
```
81+
`str +=` should be avoided.
82+
83+
## Package structure
84+
85+
The entry file of a package is named after it - `config/config.go`, `watcher/watcher.go`, that kind of thing.
86+
87+
Sub-packages that implement CLI commands register themselves through `init()` by calling `commands.List.Push(&def)`.
88+
The `init.go` file at the project root imports them with a blank identifier to trigger all of that.
89+
90+
## Annotations
91+
92+
- `// NOTE: ` - Workarounds and non-obvious choices.
93+
- `// TODO: ` - Incomplete features.
94+
- `// BUG: ` - Known issues.
95+
96+
## Other bits
97+
98+
- **Mutex**: `sync.Mutex` with `Lock()`/`defer Unlock()` on types that get accessed from different goroutines.
99+
- **Generics**: A `call[TResult any]()` helper in `websocket/socket.go` cuts down on boilerplate for the typed socket methods:
100+
```go
101+
func call[TResult any](this *SSocket, method TMethod, params any, callback func(*TResult)) {
102+
var message = this.send(method, params)
103+
var response = AwaitResponse[TResult](message)
104+
105+
if callback != nil {
106+
callback(response)
107+
}
108+
}
109+
```

Makefile

Lines changed: 37 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,32 @@ help: ##@help Display all commands and descriptions
4949
} \
5050
}' $(MAKEFILE_LIST)
5151

52+
list: ##@help List all targets and their commands
53+
@awk 'BEGIN { \
54+
target = ""; cmds = ""; \
55+
} \
56+
/^[.a-zA-Z_-]+:/ && !/^\.PHONY/ { \
57+
if (target != "" && cmds != "") { \
58+
printf " \033[36m%-15s\033[0m\n%s\n", target, cmds; \
59+
} \
60+
split($$0, a, ":"); \
61+
target = (a[1] == "help" || a[1] == "list") ? "" : a[1]; \
62+
cmds = ""; \
63+
} \
64+
/^\t/ && target != "" { \
65+
cmds = cmds " " substr($$0, 2) "\n"; \
66+
} \
67+
END { \
68+
if (target != "" && cmds != "") { \
69+
printf " \033[36m%-15s\033[0m\n%s\n", target, cmds; \
70+
} \
71+
}' $(MAKEFILE_LIST)
72+
5273
version: ##@help Log the current version
5374
@echo "v$(CURRENT_VERSION_PATCH)"
5475

5576
# proto: ##@help For prototyping makefile functionality
56-
# @echo hello "$@"
77+
# @echo hello $1
5778

5879
# -- Git --
5980
.PHONY: git-graph adog
@@ -62,22 +83,27 @@ git-graph: ##@git Log decorated graph
6283
git log --all --decorate --oneline --graph
6384
# git log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(auto)%d%C(reset)' --all
6485

65-
# -- Project --
66-
.PHONY: run wrun debug test build-win build-linux build-mac build
86+
# -- Run --
87+
.PHONY: run debug test wrun
6788

68-
WGO_INCLUDE := -file .go -file .toml
89+
WGO_INCLUDE := -file .go -file .toml -file Makefile
6990

7091
run: ##@run Run normally. Pass arguments like so: args="arg1 arg2 ...".
71-
go run ./main.go $(args)
92+
go run . $(args)
93+
94+
debug: ##@run Run with --test $(testargs).
95+
go run . $(args) --test $(testargs)
7296

73-
wrun: ##@run Run and watch for file changes. Requires wgo: https://github.com/bokwoon95/wgo
74-
wgo $(WGO_INCLUDE) go run ./main.go $(args)
97+
test: ##@run go test $(args); for all packaged that contain at least 1 *_test.go script.
98+
go test $(args) $$(go list -f '{{if len .TestGoFiles}}{{.ImportPath}}{{end}}' ./...)
7599

76-
debug: ##@run Run and watch with the --test flag. Requires wgo: https://github.com/bokwoon95/wgo
77-
wgo $(WGO_INCLUDE) go run . $(args) --test
100+
wrun: ##@run Run a make target and restart on file change. make wrun <wgoargs="args..."> target=[TARGET]. Requires wgo: https://github.com/bokwoon95/wgo
101+
wgo $(WGO_INCLUDE) $(wgoargs) $(MAKE) $(target)
102+
wrunstdin: ##@run Run a make wrun with wgoargs -stdin.
103+
$(MAKE) wrun wgoargs="-stdin $(wgoargs)" target="$(target)"
78104

79-
test: ##@run go test and watch. Requires wgo: https://github.com/bokwoon95/wgo
80-
wgo $(WGO_INCLUDE) go test -v ./...
105+
# -- Build --
106+
.PHONY: build-win build-linux build-mac build
81107

82108
build-win: ##@build Build for windows. Binary will be located at ./build/
83109
GOOS=windows GOARCH=amd64 go build -o ./build/BitburnerGoFilesync_win.exe ./main.go

README.md

Lines changed: 69 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,9 @@ Current automated triggers:
1818
### Reasons to use this instead
1919

2020
- The only thing you are required to install is [the latest release](https://github.com/CTNOriginals/BitburnerGoFilesync/releases) of this project.
21-
- The only files that are required to be present on your system for this tool to work are: the executable and optionally a config file to change the default config fields.
22-
- Because this is written in golang, the tool is way lighter for your system to run, and way faster than javascript could ever be executed. The speed at which this tool can operate is only limited to how fast bitburner is able to respond back to it.
21+
- The only files that are required to be present on your system for this tool to work are: the executable and a config file.
22+
- Because this is written in golang, the tool is way lighter for your system to run, and way faster than javascript could ever be executed.
23+
The speed at which this tool can operate is only limited to how fast bitburner is able to respond back to it.
2324
- The executable can be anywhere you like, as long as you can execute it from the commandline to start it.
2425

2526

@@ -42,9 +43,12 @@ you may also clone this repository and [run/build it yourself](#how-to-build).
4243

4344
## Usage
4445

45-
Once the executable is installed you are ready to get started with the game, the only thing you would still need to do is start the filesyncer via the commandline that you should have opened in step 3 of the installation guide.
46+
Once the executable is installed you are ready to get started with the game.
47+
The only thing you would still need to do is start the filesyncer via the commandline that you should have opened in step 3 of the installation guide.
4648

47-
Simply enter `BitburnerGoFilesync.exe` (or whatever the executable is called on your system) and pass in any arguments that you like to run it with.
49+
Simply enter `BitburnerGoFilesync_<os>`
50+
(replace `<os>` with your operating system: `win.exe`, `linux` or `mac`)
51+
and optionally pass in any [Arguments](#arguments).
4852

4953
## Config
5054

@@ -66,114 +70,83 @@ The config file by default will be named `config.toml` and the initial content w
6670
| Directory | Specify the directory where this tool should watch for file changes to sync up with bitburner. | `"./"` |
6771
| FileScanInterval | The amount of miliseconds the file scanner waits each loop. | `1000` |
6872
| [FilePatterns] | Holds include and exclude file pattern matching fields which allow you to define which files to sync and which not to. | [Pattern matching rules](https://github.com/bmatcuk/doublestar?tab=readme-ov-file#patterns) |
69-
| - Include | Which files should be included. | `["*.js", "*.ts"]` |
70-
| - Exclude | Which files to ignore. This is checked before the include patterns. | `["*.d.ts"]` |
73+
| - Include | Which files should be included. | `["**/*.js", "**/*.ts"]` |
74+
| - Exclude | Which files to ignore. This is checked before the include patterns. | `["**/*.d.ts"]` |
75+
| [Logging] | Control what is and isnt logged | |
76+
| - NoColor | Prevent the logger from applying ansi color coding to the log prefix. | `false` |
7177

7278
## How to build
7379

7480
### Requirements
7581
- [golang](https://go.dev/doc/install): To be able to run the project.
76-
- (Optional) [wgo](https://github.com/bokwoon95/wgo): This is required for some Makefile targets.
77-
<br>It is a tool that also watches the project for file changes and restarts it once anything is detected.
82+
- (Optional) [make](https://en.wikipedia.org/wiki/Make_(software)): To be able to run the tool with preset macros made by me, it just *make*s it a lot easier.
83+
- (Optional) [wgo](https://github.com/bokwoon95/wgo): This is used for some Makefile targets to automatically restart the target on file change.
7884

7985
Once you have a clone of this repository and you installed the "*long list*" of requirements you can run the project in one of two ways:
80-
1. Use `make [target]`.
81-
<br>To see all possible targets and their descriptions, run `make help`.
82-
2. Manually type out what you want to run.
83-
<br>This would be something along the lines of `go run . --arg1 param --arg2 ...`.
86+
1. Manually type out what you want to run.
87+
This would be something along the lines of `go run . --arg1 param --arg2 ...`.
88+
2. Use `make [target]` (Requires `make` to be installed).
89+
To see all possible targets and their descriptions, run `make help` or `make list`.
8490

8591
If you are looking to contribute, please read the [Contribution Guidelines](https://github.com/CTNOriginals/BitburnerGoFilesync?tab=readme-ov-file).
8692

8793
## Arguments
8894

89-
This is the text that will pop up if you enter `--full-help` in the commandline arguments
90-
```
91-
Formatting Rules:
92-
Each new argument always has to start with a double dash '--'.
93-
If the argument does not start with '--' it is considered a parameter
94-
for the most recent argument that started with '--'.
95-
96-
Each argument may have any number of parameters,
97-
to check what an argument may accept or require,
98-
you can do --help followed by the name of the argument without the '--'.
99-
100-
Some arguments may accept a specific amount of parameters where others accept a range.
101-
If an argument doesnt have its required parameters, it will say so in the console,
102-
this argument will not execute anything after that and will be ignored.
103-
If you pass in more parameters than an argument needs, it simply ignores the overflow.
104-
105-
--help, --wtf:
106-
Prints a list of arguments and their descriptions.
107-
Follow it up with another argument (without the -- before it)
108-
to get a more detailed explanation about that argument.
109-
Parameters:
110-
command:
111-
The name (without the -- before it) of a command.
112-
Print a detailed explanation about a specific command.
113-
114-
--full-help, --fhelp:
115-
The same as --help, but it also includes all of the extra information
116-
as if you entered --help <command> for each argument.
117-
118-
--config:
119-
Define the config.toml file path.
120-
By default, the config file is located in the same directory as the binary.
121-
If no config file exists at the specified location, one will be created.
122-
Parameters:
123-
filepath:
124-
The path to the config file
125-
Default: /home/ctn/code/bitburner/gofilesync/config.toml
126-
127-
--dir:
128-
Specify the directory where this tool should watch
129-
for file changes to sync up with bitburner
130-
Parameters:
131-
dir:
132-
The path to the directory where you keep your bitburner scripts.
133-
Make sure to surround this parameter with double quotes (").
134-
135-
--include-ext, --ext:
136-
Specify which file extensions the file watcher should include.
137-
Default: js ts txt
138-
Parameters:
139-
extensions:
140-
Any number of file extensions separated with spaces.
141-
Example: js ts json
142-
143-
--port:
144-
Set the port for the server to connect to.
145-
By default, the server will try to connect to 'localhost:8080'.
146-
Parameters:
147-
port:
148-
The port number.
149-
Default: 8080
150-
151-
--scan-interval, --interval:
152-
The amount of miliseconds the file scanner waits each loop.
153-
By default 100, if <= 0 it will skip the sleep function entirely.
154-
Parameters:
155-
interval:
156-
The interval in miliseconds
157-
Default: 100
158-
159-
--get-definitions:
160-
Requests the NetscriptDefinitions.d.ts file when a connection is established.
161-
The definitions file will be created in bitburners root directory.
95+
The following block is the output of `--help` in the commandline arguments.
96+
For more detailed descriptions, use `--full-help` or `--help <command>`.
97+
```md
98+
Formatting Rules Each new argument always has to start with a double dash '--'.
99+
If the argument does not start with '--' it is considered a parameter
100+
for the most recent argument that started with '--'.
101+
102+
Each argument may have any number of parameters,
103+
to check what an argument may accept or require,
104+
you can do --help followed by the name of the argument without the '--'.
105+
106+
Some arguments may accept a specific amount of parameters where others accept a range.
107+
If an argument doesnt have its required parameters, it will say so in the console,
108+
this argument will not execute anything after that and will be ignored.
109+
If you pass in more parameters than an argument needs, it simply ignores the overflow.
110+
111+
--help --wtf Prints a list of arguments and their descriptions.
112+
Follow it up with another argument (without the -- before it)
113+
to get a more detailed explanation about that argument.
114+
115+
--full-help The same as --help, but it also includes all of the extra information
116+
--fhelp as if you entered --help <command> for each argument.
117+
118+
--config Define the config.toml file path.
119+
By default, the config file is located in the same directory as the binary.
120+
If no config file exists at the specified location, one will be created.
121+
122+
--dir Specify the directory where this tool should watch
123+
for file changes to sync up with bitburner
124+
125+
--include-ext Specify which file extensions the file watcher should include.
126+
--ext Default: js ts txt
127+
128+
--port Set the port for the server to connect to.
129+
By default, the server will try to connect to 'localhost:8080'.
130+
131+
--scan-interval The amount of miliseconds the file scanner waits each loop.
132+
--interval By default 100, if <= 0 it will skip the sleep function entirely.
133+
134+
--get-definitions Currently not functional.
135+
Requests the NetscriptDefinitions.d.ts file when a connection is established.
136+
The definitions file will be created in bitburners root directory.
162137

163138
DEBUG ARGUMENTS
164139

165-
--test, --debug:
166-
Runs the test function if it exists
140+
--test Runs the test and with the provided inputs.
141+
142+
--debug Enables debug mode, mostly means that debug logs will be printed.
143+
144+
--no-watcher Prevents the program from watching file events.
167145

168-
--no-watcher:
169-
Prevents the program from watching file events.
146+
--no-server Prevents the program from creating a server and connecting to bitburner.
147+
--no-client
148+
--no-websocket
170149

171-
--no-server:
172-
Prevents the program from creating a server and connecting to bitburner.
173-
Parameters:
174-
keep-alive:
175-
Accepts: true, false
176-
Usually when a server is ran, the program wont exit as it keeps evaluating it,
177-
if this parameter is set to true, the program will still be prevented from exiting.
150+
--no-cli Prevents the program running the cli.
178151
```
179152

0 commit comments

Comments
 (0)