Skip to content

Commit

Permalink
Add Formatting and Linting to Launcher (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
VirajP1002 authored Apr 15, 2024
1 parent ec376d0 commit def7aca
Show file tree
Hide file tree
Showing 20 changed files with 2,562 additions and 703 deletions.
3 changes: 3 additions & 0 deletions .djlintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"ignore": "H006"
}
35 changes: 35 additions & 0 deletions .github/workflows/pull_request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,41 @@ jobs:
run: go get
- name: Build
run: CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo
lint:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.21'
cache: false
- name: Go linting
uses: golangci/golangci-lint-action@v4
with:
version: v1.57
- uses: actions/setup-node@v3
with:
node-version-file: ".nvmrc"
cache: "npm"
- name: Install npm deps
run: npm install
- name: Install Poetry
uses: snok/install-poetry@v1
with:
version: 1.8.2
virtualenvs-create: true
- uses: actions/setup-python@v4
with:
python-version: ${{ env.PYTHON_VERSION }}
cache: 'poetry'
- name: Install virtual environment
run: |
sudo apt-get install libsnappy-dev
poetry install
- name: Templates linting
run: make lint-templates
- name: Static linting
run: make lint-static
docker-push:
runs-on: ubuntu-22.04
steps:
Expand Down
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v20.10.0
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#Ignore any html files
**/*.html
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.11.4
22 changes: 22 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
lint: lint-go lint-templates lint-static

format: format-go format-static format-templates

format-go:
go fmt ./...

lint-go:
golangci-lint run

lint-static:
npx prettier --check "static/**/*.{js,css}"
npx eslint static/javascript/*.js

format-static:
npx prettier "static/**/*.{js,css}" --write

lint-templates:
poetry run djlint templates --lint

format-templates:
poetry run djlint templates/*.html --reformat
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,37 @@ Documentation on the `v2` structure can be found [here](https://github.com/ONSdi
e.g."http://localhost:8000/quick-launch?schema_url=http://localhost:7777/1_0001.json&version=v1"
```

### Commands for Formatting & Linting
Ensure you are using the correct version of node using:
``` shell
nvm install
nvm use
```
To install ESLint and Prettier for formatting and linting of static files use:
``` shell
npm install
```
Firstly, ensure you have Python & Poetry installed and then install djLint for formatting and linting template files using:
```shell
poetry install
```

**Note**: Before being able to run `lint-go`,
you will need to install the external tool `golangci-lint`. The command to install the tool is
`brew install golangci-lint` and to upgrade it use `brew upgrade golangci-lint`. Visit
https://golangci-lint.run/welcome/install/#local-installation to see additional ways to install the tool.

| Command | Task |
|-------------------------|---------------------------------------------------------|
| `make format-static` | Formats all static files (Javascipt and CSS) |
| `make format-templates` | Formats all HTML files and shows the changes to be made |
| `make format-go` | Formats all the Golang files |
| `make format` | Formats all files listed above |
| `make lint-static` | Lints all static files and reports any issues |
| `make lint-templates` | Lints all HTML files and reports any issues |
| `make lint-go` | Lints all Golang files using an external tool |
| `make lint` | Lints all files listed above |

### Notes
* There are no unit tests yet
* JWT spec based on http://ons-schema-definitions.readthedocs.io/en/latest/jwt_profile.html
Expand Down
27 changes: 12 additions & 15 deletions authentication/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ import (
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"io"
"math/rand"
"net/http"
"net/url"
"os"
"time"

"github.com/ONSdigital/eq-questionnaire-launcher/clients"
Expand Down Expand Up @@ -59,7 +60,7 @@ type PrivateKeyResult struct {
func loadEncryptionKey() (*PublicKeyResult, *KeyLoadError) {
encryptionKeyPath := settings.Get("JWT_ENCRYPTION_KEY_PATH")

keyData, err := ioutil.ReadFile(encryptionKeyPath)
keyData, err := os.ReadFile(encryptionKeyPath)
if err != nil {
return nil, &KeyLoadError{Op: "read", Err: "Failed to read encryption key from file: " + encryptionKeyPath}
}
Expand All @@ -82,7 +83,7 @@ func loadEncryptionKey() (*PublicKeyResult, *KeyLoadError) {

func loadSigningKey() (*PrivateKeyResult, *KeyLoadError) {
signingKeyPath := settings.Get("JWT_SIGNING_KEY_PATH")
keyData, err := ioutil.ReadFile(signingKeyPath)
keyData, err := os.ReadFile(signingKeyPath)
if err != nil {
return nil, &KeyLoadError{Op: "read", Err: "Failed to read signing key from file: " + signingKeyPath}
}
Expand Down Expand Up @@ -251,7 +252,7 @@ func launcherSchemaFromURL(url string) (launcherSchema surveys.LauncherSchema, e
return launcherSchema, fmt.Sprintf("Failed to load Schema from %s", url)
}

responseBody, err := ioutil.ReadAll(resp.Body)
responseBody, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
panic(err)
Expand Down Expand Up @@ -311,7 +312,7 @@ func validateSchema(payload []byte) (error string) {
return err.Error()
}

responseBody, err := ioutil.ReadAll(resp.Body)
responseBody, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return err.Error()
Expand Down Expand Up @@ -421,10 +422,9 @@ func GenerateTokenFromDefaults(schemaURL string, accountServiceURL string, accou
return "", validationError
}

claims := make(map[string]interface{})
urlValues["account_service_url"] = []string{accountServiceURL}
urlValues["account_service_log_out_url"] = []string{accountServiceLogOutURL}
claims = generateClaims(urlValues, launcherSchema)
claims := generateClaims(urlValues, launcherSchema)

requiredMetadata, error := getRequiredSchemaMetadata(launcherSchema)
if error != "" {
Expand Down Expand Up @@ -469,10 +469,9 @@ func GenerateTokenFromDefaultsV2(schemaURL string, accountServiceURL string, url
return "", fmt.Sprintf("getSchema failed err: %v", error)
}

claims := make(map[string]interface{})
urlValues["account_service_url"] = []string{accountServiceURL}

claims = generateClaimsV2(urlValues, schema)
claims := generateClaimsV2(urlValues, schema)

requiredSchemaMetadata, error := getRequiredSchemaMetadata(launcherSchema)
if error != "" {
Expand Down Expand Up @@ -566,7 +565,7 @@ func GenerateTokenFromPost(postValues url.Values, launchVersion2 bool) (string,
return "", fmt.Sprintf("getSchema failed err: %v", error)
}

claims := make(map[string]interface{})
var claims map[string]interface{}

if launchVersion2 {
claims = generateClaimsV2(postValues, schema)
Expand Down Expand Up @@ -642,9 +641,7 @@ func GetSurveyData(launcherSchema surveys.LauncherSchema) (QuestionnaireSchema,

missingClaims := getMissingMandatoryClaims(claims, mandatoryClaims)

for _, v := range missingClaims {
schema.Metadata = append(schema.Metadata, v)
}
schema.Metadata = append(schema.Metadata, missingClaims...)

return schema, ""
}
Expand Down Expand Up @@ -686,7 +683,7 @@ func getSchema(launcherSchema surveys.LauncherSchema) (QuestionnaireSchema, stri
return schema, fmt.Sprintf("Failed to load Schema from %s", url)
}

responseBody, err := ioutil.ReadAll(resp.Body)
responseBody, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Print(err)
Expand All @@ -702,7 +699,7 @@ func getSchema(launcherSchema surveys.LauncherSchema) (QuestionnaireSchema, stri
}

func getMandatatoryClaims(surveyType string, defaults map[string]string) []Metadata {
claims := make([]Metadata, 0)
var claims []Metadata
if isSocialSurvey(surveyType) {
claims = []Metadata{
{"qid", "false", defaults["qid"]},
Expand Down
4 changes: 2 additions & 2 deletions clients/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ var httpClient = &http.Client{
}

// GetHTTPClient returns a single HttpClient for use across the app
func GetHTTPClient() (*http.Client) {
func GetHTTPClient() *http.Client {
return httpClient
}
}
22 changes: 17 additions & 5 deletions launch.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,11 @@ type page struct {
}

func getStatusPage(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("OK"))
_, writeError := w.Write([]byte("OK"))
if writeError != nil {
http.Error(w, fmt.Sprintf("Write failed to write data as part of an HTTP reply: %v", writeError), 500)
return
}
}

func getLaunchHandler(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -102,7 +106,11 @@ func getSurveyDataHandler(w http.ResponseWriter, r *http.Request) {

surveyDataJSON, _ := json.Marshal(surveyData)

w.Write([]byte(surveyDataJSON))
_, writeError := w.Write([]byte(surveyDataJSON))
if writeError != nil {
http.Error(w, fmt.Sprintf("Write failed to write data as part of an HTTP reply: %v", writeError), 500)
return
}
}

func getSupplementaryDataHandler(w http.ResponseWriter, r *http.Request) {
Expand All @@ -116,7 +124,11 @@ func getSupplementaryDataHandler(w http.ResponseWriter, r *http.Request) {
}
datasetJSON, _ := json.Marshal(datasets)

w.Write([]byte(datasetJSON))
_, writeError := w.Write([]byte(datasetJSON))
if writeError != nil {
http.Error(w, fmt.Sprintf("Write failed to write data as part of an HTTP reply: %v", writeError), 500)
return
}
}

func getAccountServiceURL(r *http.Request) string {
Expand Down Expand Up @@ -160,7 +172,7 @@ func redirectURL(w http.ResponseWriter, r *http.Request) {
} else if launchVersion != "" {
http.Redirect(w, r, hostURL+"/session?token="+token, 301)
} else {
http.Error(w, fmt.Sprintf("Invalid Action"), 500)
http.Error(w,"Invalid Action", 500)
}
}

Expand Down Expand Up @@ -209,7 +221,7 @@ func quickLauncherHandler(w http.ResponseWriter, r *http.Request) {
if schemaURL != "" {
http.Redirect(w, r, hostURL+"/session?token="+token, 302)
} else {
http.Error(w, fmt.Sprintf("Not Found"), 404)
http.Error(w, "Not Found", 404)
}
}

Expand Down
4 changes: 0 additions & 4 deletions lint.sh

This file was deleted.

Loading

0 comments on commit def7aca

Please sign in to comment.