Skip to content

Commit a69c4a4

Browse files
author
Luca Bianconi
committed
refactor: cleanup
1 parent d7ec61e commit a69c4a4

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

Diff for: commands/sketch/new.go

+19-11
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,9 @@ void loop() {
3535
}
3636
`)
3737

38-
var sketchNameValidationRegex = regexp.MustCompile(`^([A-Za-z\d]+[_.-]*)+$`)
38+
// sketchNameMaxLength could be part of the regex, but it's intentionally left out for clearer error reporting
3939
var sketchNameMaxLength = 63
40+
var sketchNameValidationRegex = regexp.MustCompile(`^[0-9a-zA-Z]{1}[0-9a-zA-Z_\.-]*$`)
4041

4142
// NewSketch creates a new sketch via gRPC
4243
func NewSketch(ctx context.Context, req *rpc.NewSketchRequest) (*rpc.NewSketchResponse, error) {
@@ -47,16 +48,8 @@ func NewSketch(ctx context.Context, req *rpc.NewSketchRequest) (*rpc.NewSketchRe
4748
sketchesDir = configuration.Settings.GetString("directories.User")
4849
}
4950

50-
if len(req.SketchName) > sketchNameMaxLength {
51-
return nil, &arduino.CantCreateSketchError{Cause: errors.New(tr("sketch name too long (%d characters). Maximum allowed length is %d",
52-
len(req.SketchName),
53-
sketchNameMaxLength))}
54-
}
55-
56-
if !sketchNameValidationRegex.MatchString(req.SketchName) {
57-
return nil, &arduino.CantCreateSketchError{Cause: errors.New(tr("invalid sketch name \"%s\". Required pattern %s",
58-
req.SketchName,
59-
sketchNameValidationRegex.String()))}
51+
if err := validateSketchName(req.SketchName); err != nil {
52+
return nil, err
6053
}
6154

6255
sketchDirPath := paths.New(sketchesDir).Join(req.SketchName)
@@ -76,3 +69,18 @@ func NewSketch(ctx context.Context, req *rpc.NewSketchRequest) (*rpc.NewSketchRe
7669

7770
return &rpc.NewSketchResponse{MainFile: sketchMainFilePath.String()}, nil
7871
}
72+
73+
func validateSketchName(name string) error {
74+
if len(name) > sketchNameMaxLength {
75+
return &arduino.CantCreateSketchError{Cause: errors.New(tr("sketch name too long (%d characters). Maximum allowed length is %d",
76+
len(name),
77+
sketchNameMaxLength))}
78+
}
79+
80+
if !sketchNameValidationRegex.MatchString(name) {
81+
return &arduino.CantCreateSketchError{Cause: errors.New(tr("invalid sketch name \"%s\". Required pattern %s",
82+
name,
83+
sketchNameValidationRegex.String()))}
84+
}
85+
return nil
86+
}

0 commit comments

Comments
 (0)