Skip to content

Commit 673df61

Browse files
committed
back out some non-idiomatic one lining but add helper functions to make some stuff easier to read
Signed-off-by: Callum Styan <[email protected]>
1 parent 9fd7eb4 commit 673df61

File tree

4 files changed

+38
-47
lines changed

4 files changed

+38
-47
lines changed

cmd/readmevalidation/coderresources.go

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,21 @@ func validateCoderResourceDescription(description string) error {
5656
return nil
5757
}
5858

59+
func isPermittedRelativeURL(checkURL string) bool {
60+
// Would normally be skittish about having relative paths like this, but it should be safe because we have
61+
// guarantees about the structure of the repo, and where this logic will run.
62+
return strings.HasPrefix(checkURL, "./") || strings.HasPrefix(checkURL, "/") || strings.HasPrefix(checkURL, "../../../../.icons")
63+
}
64+
5965
func validateCoderResourceIconURL(iconURL string) []error {
6066
if iconURL == "" {
6167
return []error{xerrors.New("icon URL cannot be empty")}
6268
}
6369

6470
errs := []error{}
6571

66-
isAbsoluteURL := !strings.HasPrefix(iconURL, ".") && !strings.HasPrefix(iconURL, "/")
67-
if isAbsoluteURL {
72+
// If the URL does not have a relative path.
73+
if !strings.HasPrefix(iconURL, ".") && !strings.HasPrefix(iconURL, "/") {
6874
if _, err := url.ParseRequestURI(iconURL); err != nil {
6975
errs = append(errs, xerrors.New("absolute icon URL is not correctly formatted"))
7076
}
@@ -74,12 +80,8 @@ func validateCoderResourceIconURL(iconURL string) []error {
7480
return errs
7581
}
7682

77-
// Would normally be skittish about having relative paths like this, but it should be safe because we have guarantees
78-
// about the structure of the repo, and where this logic will run.
79-
isPermittedRelativeURL := strings.HasPrefix(iconURL, "./") ||
80-
strings.HasPrefix(iconURL, "/") ||
81-
strings.HasPrefix(iconURL, "../../../../.icons")
82-
if !isPermittedRelativeURL {
83+
// If the URL has a relative path.
84+
if !isPermittedRelativeURL(iconURL) {
8385
errs = append(errs, xerrors.Errorf("relative icon URL %q must either be scoped to that module's directory, or the top-level /.icons directory (this can usually be done by starting the path with \"../../../.icons\")", iconURL))
8486
}
8587

@@ -271,7 +273,7 @@ func parseCoderResourceReadmeFiles(resourceType string, rms []readme) (map[strin
271273

272274
// Todo: Need to beef up this function by grabbing each image/video URL from
273275
// the body's AST.
274-
func validateCoderResourceRelativeUrls(_ map[string]coderResourceReadme) error {
276+
func validateCoderResourceRelativeURLs(_ map[string]coderResourceReadme) error {
275277
return nil
276278
}
277279

@@ -283,14 +285,13 @@ func aggregateCoderResourceReadmeFiles(resourceType string) ([]readme, error) {
283285

284286
var allReadmeFiles []readme
285287
var errs []error
286-
var resourceDirs []os.DirEntry
287288
for _, rf := range registryFiles {
288289
if !rf.IsDir() {
289290
continue
290291
}
291292

292293
resourceRootPath := path.Join(rootRegistryPath, rf.Name(), resourceType)
293-
resourceDirs, err = os.ReadDir(resourceRootPath)
294+
resourceDirs, err := os.ReadDir(resourceRootPath)
294295
if err != nil {
295296
if !errors.Is(err, os.ErrNotExist) {
296297
errs = append(errs, err)
@@ -343,7 +344,7 @@ func validateAllCoderResourceFilesOfType(resourceType string) error {
343344
}
344345
logger.Info(context.Background(), "rocessed README files as valid Coder resources", "num_files", len(resources), "type", resourceType)
345346

346-
if err = validateCoderResourceRelativeUrls(resources); err != nil {
347+
if err := validateCoderResourceRelativeURLs(resources); err != nil {
347348
return err
348349
}
349350
logger.Info(context.Background(), "all relative URLs for READMEs are valid", "type", resourceType)

cmd/readmevalidation/contributors.go

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ func validateContributorAvatarURL(avatarURL *string) []error {
128128
errs = append(errs, xerrors.New("avatar URL is not allowed to contain search parameters"))
129129
}
130130

131-
matched := false
131+
var matched bool
132132
for _, ff := range supportedAvatarFileFormats {
133133
matched = strings.HasSuffix(*avatarURL, ff)
134134
if matched {
@@ -243,7 +243,6 @@ func aggregateContributorReadmeFiles() ([]readme, error) {
243243
}
244244

245245
dirPath = path.Join(rootRegistryPath, e.Name())
246-
247246
readmePath := path.Join(dirPath, "README.md")
248247
rmBytes, err := os.ReadFile(readmePath)
249248
if err != nil {
@@ -288,8 +287,7 @@ func validateContributorRelativeURLs(contributors map[string]contributorProfileR
288287
continue
289288
}
290289

291-
absolutePath := strings.TrimSuffix(con.filePath, "README.md") +
292-
*con.frontmatter.AvatarURL
290+
absolutePath := strings.TrimSuffix(con.filePath, "README.md") + *con.frontmatter.AvatarURL
293291
if _, err := os.ReadFile(absolutePath); err != nil {
294292
errs = append(errs, xerrors.Errorf("%q: relative avatar path %q does not point to image in file system", con.filePath, absolutePath))
295293
}
@@ -317,7 +315,7 @@ func validateAllContributorFiles() error {
317315
}
318316
logger.Info(context.Background(), "processed README files as valid contributor profiles", "num_contributors", len(contributors))
319317

320-
if err = validateContributorRelativeURLs(contributors); err != nil {
318+
if err := validateContributorRelativeURLs(contributors); err != nil {
321319
return err
322320
}
323321
logger.Info(context.Background(), "all relative URLs for READMEs are valid")

cmd/readmevalidation/readmefiles.go

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"bufio"
5+
"fmt"
56
"regexp"
67
"strings"
78

@@ -21,15 +22,15 @@ const (
2122
// system as expected.
2223
validationPhaseStructure validationPhase = "File structure validation"
2324

24-
// validationPhaseFile indicates when README files are being read from
25+
// ValidationPhaseFile indicates when README files are being read from
2526
// the file system.
2627
validationPhaseFile validationPhase = "Filesystem reading"
2728

28-
// validationPhaseReadme indicates when a README's frontmatter is
29+
// ValidationPhaseReadme indicates when a README's frontmatter is
2930
// being parsed as YAML. This phase does not include YAML validation.
3031
validationPhaseReadme validationPhase = "README parsing"
3132

32-
// validationPhaseCrossReference indicates when a README's frontmatter
33+
// ValidationPhaseCrossReference indicates when a README's frontmatter
3334
// is having all its relative URLs be validated for whether they point to
3435
// valid resources.
3536
validationPhaseCrossReference validationPhase = "Cross-referencing relative asset URLs"
@@ -58,14 +59,13 @@ func separateFrontmatter(readmeText string) (readmeFrontmatter string, readmeBod
5859

5960
const fence = "---"
6061

61-
fm := ""
62-
body := ""
63-
nextLine := ""
62+
var fm strings.Builder
63+
var body strings.Builder
6464
fenceCount := 0
6565

6666
lineScanner := bufio.NewScanner(strings.NewReader(strings.TrimSpace(readmeText)))
6767
for lineScanner.Scan() {
68-
nextLine = lineScanner.Text()
68+
nextLine := lineScanner.Text()
6969
if fenceCount < 2 && nextLine == fence {
7070
fenceCount++
7171
continue
@@ -79,19 +79,19 @@ func separateFrontmatter(readmeText string) (readmeFrontmatter string, readmeBod
7979
// extra meaning attached to the indentation. The same does NOT apply to the README; best we can do is gather
8080
// all the lines and then trim around it.
8181
if inReadmeBody := fenceCount >= 2; inReadmeBody {
82-
body += nextLine + "\n"
82+
fmt.Fprintf(&body, "%s\n", nextLine)
8383
} else {
84-
fm += strings.TrimSpace(nextLine) + "\n"
84+
fmt.Fprintf(&fm, "%s\n", strings.TrimSpace(nextLine))
8585
}
8686
}
8787
if fenceCount < 2 {
8888
return "", "", xerrors.New("README does not have two sets of frontmatter fences")
8989
}
90-
if fm == "" {
90+
if fm.Len() == 0 {
9191
return "", "", xerrors.New("readme has frontmatter fences but no frontmatter content")
9292
}
9393

94-
return fm, strings.TrimSpace(body), nil
94+
return fm.String(), strings.TrimSpace(body.String()), nil
9595
}
9696

9797
// TODO: This seems to work okay for now, but the really proper way of doing this is by parsing this as an AST, and then
@@ -113,11 +113,10 @@ func validateReadmeBody(body string) []error {
113113
latestHeaderLevel := 0
114114
foundFirstH1 := false
115115
isInCodeBlock := false
116-
nextLine := ""
117116

118117
lineScanner := bufio.NewScanner(strings.NewReader(trimmed))
119118
for lineScanner.Scan() {
120-
nextLine = lineScanner.Text()
119+
nextLine := lineScanner.Text()
121120

122121
// Have to check this because a lot of programming languages support # comments (including Terraform), and
123122
// without any context, there's no way to tell the difference between a markdown header and code comment.

cmd/readmevalidation/repostructure.go

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,8 @@ import (
1313
var supportedUserNameSpaceDirectories = append(supportedResourceTypes, ".icons", ".images")
1414

1515
func validateCoderResourceSubdirectory(dirPath string) []error {
16-
var (
17-
err error
18-
subDir os.FileInfo
19-
)
20-
21-
if subDir, err = os.Stat(dirPath); err != nil {
16+
subDir, err := os.Stat(dirPath)
17+
if err != nil {
2218
// It's valid for a specific resource directory not to exist. It's just that if it does exist, it must follow specific rules.
2319
if !errors.Is(err, os.ErrNotExist) {
2420
return []error{addFilePathToError(dirPath, err)}
@@ -43,7 +39,7 @@ func validateCoderResourceSubdirectory(dirPath string) []error {
4339
}
4440

4541
resourceReadmePath := path.Join(dirPath, f.Name(), "README.md")
46-
if _, err = os.Stat(resourceReadmePath); err != nil {
42+
if _, err := os.Stat(resourceReadmePath); err != nil {
4743
if errors.Is(err, os.ErrNotExist) {
4844
errs = append(errs, xerrors.Errorf("%q: 'README.md' does not exist", resourceReadmePath))
4945
} else {
@@ -52,7 +48,7 @@ func validateCoderResourceSubdirectory(dirPath string) []error {
5248
}
5349

5450
mainTerraformPath := path.Join(dirPath, f.Name(), "main.tf")
55-
if _, err = os.Stat(mainTerraformPath); err != nil {
51+
if _, err := os.Stat(mainTerraformPath); err != nil {
5652
if errors.Is(err, os.ErrNotExist) {
5753
errs = append(errs, xerrors.Errorf("%q: 'main.tf' file does not exist", mainTerraformPath))
5854
} else {
@@ -64,16 +60,12 @@ func validateCoderResourceSubdirectory(dirPath string) []error {
6460
}
6561

6662
func validateRegistryDirectory() []error {
67-
var (
68-
userDirs []os.DirEntry
69-
err error
70-
)
71-
if userDirs, err = os.ReadDir(rootRegistryPath); err != nil {
63+
userDirs, err := os.ReadDir(rootRegistryPath)
64+
if err != nil {
7265
return []error{err}
7366
}
7467

7568
allErrs := []error{}
76-
var iterFiles []os.DirEntry
7769
for _, d := range userDirs {
7870
dirPath := path.Join(rootRegistryPath, d.Name())
7971
if !d.IsDir() {
@@ -82,16 +74,17 @@ func validateRegistryDirectory() []error {
8274
}
8375

8476
contributorReadmePath := path.Join(dirPath, "README.md")
85-
if _, err = os.Stat(contributorReadmePath); err != nil {
77+
if _, err := os.Stat(contributorReadmePath); err != nil {
8678
allErrs = append(allErrs, err)
8779
}
8880

89-
if iterFiles, err = os.ReadDir(dirPath); err != nil {
81+
files, err := os.ReadDir(dirPath)
82+
if err != nil {
9083
allErrs = append(allErrs, err)
9184
continue
9285
}
9386

94-
for _, f := range iterFiles {
87+
for _, f := range files {
9588
// TODO: Decide if there's anything more formal that we want to ensure about non-directories scoped to user namespaces.
9689
if !f.IsDir() {
9790
continue

0 commit comments

Comments
 (0)