-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageLinter.swift
More file actions
executable file
·1744 lines (1550 loc) · 67.6 KB
/
ImageLinter.swift
File metadata and controls
executable file
·1744 lines (1550 loc) · 67.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env xcrun --sdk macosx swift
import Foundation
import AppKit
/**
ImageLinter.swift
version 2.3.2
Created by Sergey Balalaev on 23.09.22.
Copyright (c) 2022-2025 ByteriX. All rights reserved.
Using from build phase:
${SRCROOT}/Scripts/ImageLinter.swift
*/
//
// SwiftGen.swift
//
//
// Created by Sergey Balalaev on 18.04.2024.
//
import Foundation
extension String {
static let snakeSeporators = "-_"
func lowercasedFirstLetter() -> String {
return prefix(1).lowercased() + dropFirst()
}
func uppercasedFirstLetter() -> String {
return prefix(1).uppercased() + dropFirst()
}
}
fileprivate extension Array where Self.Element == String {
func swiftGenFolders() -> [Self.Element] {
guard let last = last else {
return self
}
var result: [Self.Element] = dropLast()
result.append(last.lowercasedFirstLetter())
return result
}
func swiftGenCamel() -> [Self.Element] {
guard let first = first else {
return self
}
var result: [Self.Element] = dropFirst().map { $0.uppercasedFirstLetter() }
result.insert(first, at: 0)
return result
}
}
extension String {
func swiftGenCamel() -> String {
return self
.trimmingCharacters(in: CharacterSet(charactersIn: Self.snakeSeporators))
.split(whereSeparator: { char in
Self.snakeSeporators.contains { $0 == char }
})
.map { String($0) }
.swiftGenCamel()
.joined(separator: "")
}
}
extension String {
func swiftGenKey() -> String {
return self
.split(separator: "/")
.map { String($0).swiftGenCamel() }
.swiftGenFolders()
.joined(separator: ".")
}
}
//
// Settings+Keys.swift
// Imagelinter
//
// Created by Sergey Balalaev on 23.12.2025.
//
extension Settings {
enum Key: String {
case isEnabled
case relativeImagesPaths
case relativeImagesPath
case relativeSourcePaths
case relativeSourcePath
case usingTypes
case checkingNameTypes
case ignoredUnusedImages
case ignoredUndefinedImages
case rastorExtensions
case vectorExtensions
case sourcesExtensions
case resourcesExtensions
case isAllFilesErrorShowing
case maxVectorFileSize
case maxVectorImageSize
case maxRastorFileSize
case maxRastorImageSize
case isCheckingFileSize
case isCheckingImageSize
case isCheckingPdfVector
case isCheckingSvgVector
case isCheckingScaleSize
case isCheckingDuplicatedByName
case isCheckingDuplicatedByContent
case targetPlatforms
enum UsingType: String {
case swiftUI
case uiKit
case uiKitLiteral
case swiftGen
case custom
}
enum CheckingNameType: String {
case firstUpperCase
case camelCase
case sneak_case
case kebab_case
case custom
func convert(message: String?, filter: ImageFilter?) -> Settings.CheckingNameType {
if let message {
switch self {
case .firstUpperCase: return .firstUpperCase(message: message, filter: filter)
case .camelCase: return .camelCase(message: message, filter: filter)
case .sneak_case: return .sneak_case(message: message, filter: filter)
case .kebab_case: return .kebab_case(message: message, filter: filter)
case .custom: return .custom(pattern: "", message: message, filter: filter)
}
} else {
switch self {
case .firstUpperCase: return .firstUpperCase(filter: filter)
case .camelCase: return .camelCase(filter: filter)
case .sneak_case: return .sneak_case(filter: filter)
case .kebab_case: return .kebab_case(filter: filter)
case .custom: return .custom(pattern: "", filter: filter)
}
}
}
}
enum TargetPlatform: String {
case iOS
case iPadOS
case macOS
case tvOS
case visionOS
case watchOS
}
}
}
//
// Settings+Parse.swift
// Imagelinter
//
// Created by Sergey Balalaev on 23.12.2025.
//
import Foundation
extension Settings {
mutating func load(from stringData: String) {
let lines = stringData.components(separatedBy: .newlines)
var currentKey: Key? = nil
var isStartKey: Bool = false
var lineIndex = 0
while lineIndex < lines.count {
let line = lines[lineIndex].trimmingCharacters(in: .whitespaces)
lineIndex += 1
if line.hasPrefix("#") {
continue
}
var currentValue: String? = nil
if let value = Self.getArrayValue(line: line) {
currentValue = value
} else if let object = Self.getObject(line: line) {
if let key = Key(rawValue: object.name) {
currentKey = key
currentValue = object.value
isStartKey = true
}
}
func getSize(defaultSize: CGSize) -> CGSize {
var width = defaultSize.width
var height = defaultSize.height
while lineIndex < lines.count
{
let line = lines[lineIndex].trimmingCharacters(in: .whitespaces)
if line.hasPrefix("#") == false,
let object = Self.getObject(line: line)
{
if object.name == "width" {
width = Double(object.value) ?? defaultSize.width
} else if object.name == "height" {
height = Double(object.value) ?? defaultSize.height
} else {
break
}
}
lineIndex += 1
}
return CGSize(width: width, height: height)
}
guard let currentKey else { continue }
switch currentKey {
case .isEnabled:
if let value = currentValue, let isEnabled = Bool(value) {
self.isEnabled = isEnabled
}
case .relativeImagesPath, .relativeImagesPaths:
if let value = currentValue, value != "" {
relativeImagesPaths.append(Self.pathWithSlash(value))
}
case .relativeSourcePath, .relativeSourcePaths:
if let value = currentValue, value != "" {
relativeSourcePaths.append(Self.pathWithSlash(value))
}
case .usingTypes:
if let value = currentValue, value.isEmpty == false {
if let object = Self.getObject(line: value), object.name == "case" {
if let usingType = Key.UsingType(rawValue: object.value) {
switch usingType {
case .swiftUI:
self.usingTypes.append(.swiftUI)
case .uiKit:
self.usingTypes.append(.uiKit)
case .uiKitLiteral:
self.usingTypes.append(.uiKitLiteral)
case .swiftGen:
guard lineIndex < lines.count else {
break
}
let line = lines[lineIndex].trimmingCharacters(in: .whitespaces)
if line.hasPrefix("#") == false,
let object = Self.getObject(line: line),
object.name == "enumName"
{
lineIndex += 1
self.usingTypes.append(.swiftGen(enumName: object.value))
}
case .custom:
guard lineIndex < lines.count else {
break
}
var line = lines[lineIndex].trimmingCharacters(in: .whitespaces)
var customPattern: String?
var customIsSwiftGen = false
// TODO: # needs just continue
while lineIndex < lines.count,
line.hasPrefix("#") == false,
let object = Self.getObject(line: line),
object.name == "pattern" || object.name == "isSwiftGen"
{
lineIndex += 1
if object.name == "pattern" {
customPattern = object.value
} else if object.name == "isSwiftGen", let isSwiftGen = Bool(object.value) {
customIsSwiftGen = isSwiftGen
}
if lineIndex < lines.count {
line = lines[lineIndex].trimmingCharacters(in: .whitespaces)
}
}
if let customPattern {
self.usingTypes.append(.custom(pattern: customPattern, isSwiftGen: customIsSwiftGen))
}
}
}
}
} else if isStartKey {
self.usingTypes = []
}
case .checkingNameTypes:
// TODO: # needs refactory with delete CheckingNameRegexPattern
if let value = currentValue, value.isEmpty == false {
if let object = Self.getObject(line: value), object.name == "case" {
if let checkingNameType = Key.CheckingNameType(rawValue: object.value) {
switch checkingNameType {
case .firstUpperCase, .camelCase, .sneak_case, .kebab_case:
var customMessage: String?
var customFilter: ImageFilter?
while lineIndex < lines.count {
let line = lines[lineIndex].trimmingCharacters(in: .whitespaces)
if line.hasPrefix("#") {
lineIndex += 1
continue
}
guard let object = Self.getObject(line: line),
object.name == "message" || object.name == "filter" else {
break
}
if object.name == "message" {
customMessage = object.value
} else if object.name == "filter" {
customFilter = ImageFilter(object.value)
}
lineIndex += 1
}
self.checkingNameTypes.append(checkingNameType.convert(message: customMessage, filter: customFilter))
case .custom:
guard lineIndex < lines.count else {
break
}
var line = lines[lineIndex].trimmingCharacters(in: .whitespaces)
var customPattern: String?
var customMessage: String?
var customFilter: ImageFilter?
// TODO: # needs just continue
while lineIndex < lines.count,
line.hasPrefix("#") == false,
let object = Self.getObject(line: line),
object.name == "pattern" || object.name == "message" || object.name == "filter"
{
lineIndex += 1
if object.name == "pattern" {
customPattern = object.value
} else if object.name == "message" {
customMessage = object.value
} else if object.name == "filter" {
customFilter = ImageFilter(object.value)
}
if lineIndex < lines.count {
line = lines[lineIndex].trimmingCharacters(in: .whitespaces)
}
}
if let customPattern {
if let customMessage, customMessage.isEmpty == false {
self.checkingNameTypes.append(.custom(pattern: customPattern, message: customMessage, filter: customFilter))
} else {
self.checkingNameTypes.append(.custom(pattern: customPattern, filter: customFilter))
}
}
}
}
}
} else if isStartKey {
self.checkingNameTypes = []
}
case .ignoredUnusedImages:
if let value = currentValue, value.isEmpty == false {
self.ignoredUnusedImages.insert(value)
} else if isStartKey {
self.ignoredUnusedImages = []
}
case .ignoredUndefinedImages:
if let value = currentValue, value.isEmpty == false {
self.ignoredUndefinedImages.insert(value)
} else if isStartKey {
self.ignoredUndefinedImages = []
}
case .rastorExtensions:
if let value = currentValue, value.isEmpty == false {
self.rastorExtensions.insert(value.uppercased())
} else if isStartKey {
self.rastorExtensions = []
}
case .vectorExtensions:
if let value = currentValue, value.isEmpty == false {
self.vectorExtensions.insert(value.uppercased())
} else if isStartKey {
self.vectorExtensions = []
}
case .sourcesExtensions:
if let value = currentValue, value.isEmpty == false {
self.sourcesExtensions.insert(value.uppercased())
} else if isStartKey {
self.sourcesExtensions = []
}
case .resourcesExtensions:
if let value = currentValue, value.isEmpty == false {
self.resourcesExtensions.insert(value.uppercased())
} else if isStartKey {
self.resourcesExtensions = []
}
case .isAllFilesErrorShowing:
if let value = currentValue, let isAllFilesErrorShowing = Bool(value) {
self.isAllFilesErrorShowing = isAllFilesErrorShowing
}
case .maxVectorFileSize:
if let value = currentValue, let maxVectorFileSize = UInt64(value) {
self.maxVectorFileSize = maxVectorFileSize
}
case .maxVectorImageSize:
self.maxVectorImageSize = getSize(defaultSize: self.maxVectorImageSize)
case .maxRastorFileSize:
if let value = currentValue, let maxRastorFileSize = UInt64(value) {
self.maxRastorFileSize = maxRastorFileSize
}
case .maxRastorImageSize:
self.maxRastorImageSize = getSize(defaultSize: self.maxRastorImageSize)
case .isCheckingFileSize:
if let value = currentValue, let isCheckingFileSize = Bool(value) {
self.isCheckingFileSize = isCheckingFileSize
}
case .isCheckingImageSize:
if let value = currentValue, let isCheckingImageSize = Bool(value) {
self.isCheckingImageSize = isCheckingImageSize
}
case .isCheckingPdfVector:
if let value = currentValue, let isCheckingPdfVector = Bool(value) {
self.isCheckingPdfVector = isCheckingPdfVector
}
case .isCheckingSvgVector:
if let value = currentValue, let isCheckingSvgVector = Bool(value) {
self.isCheckingSvgVector = isCheckingSvgVector
}
case .isCheckingScaleSize:
if let value = currentValue, let isCheckingScaleSize = Bool(value) {
self.isCheckingScaleSize = isCheckingScaleSize
}
case .isCheckingDuplicatedByName:
if let value = currentValue, let isCheckingDuplicatedByName = Bool(value) {
self.isCheckingDuplicatedByName = isCheckingDuplicatedByName
}
case .isCheckingDuplicatedByContent:
if let value = currentValue, let isCheckingDuplicatedByContent = Bool(value) {
self.isCheckingDuplicatedByContent = isCheckingDuplicatedByContent
}
case .targetPlatforms:
if let value = currentValue, value.isEmpty == false {
if let targetPlatform = Key.TargetPlatform(rawValue: value) {
switch targetPlatform {
case .iOS:
self.targetPlatforms.append(.iOS)
case .iPadOS:
self.targetPlatforms.append(.iPadOS)
case .macOS:
self.targetPlatforms.append(.macOS)
case .tvOS:
self.targetPlatforms.append(.tvOS)
case .visionOS:
self.targetPlatforms.append(.visionOS)
case .watchOS:
self.targetPlatforms.append(.watchOS)
}
}
} else if isStartKey {
self.targetPlatforms = []
}
}
isStartKey = false
}
}
private struct Object {
let name: String
let value: String
}
private static let regexObject = try! NSRegularExpression(pattern: #"^([A-z0-9]+?)\s*:"#, options: [.caseInsensitive])
private static func getObject(line: String) -> Object? {
let results = regexObject.matches(in: line, range: NSRange(line.startIndex..., in: line))
if let result = results.first {
let name = String(line[Range(result.range, in: line)!]).dropLast().trimmingCharacters(in: .whitespaces)
let value = line.suffix(from: Range(result.range, in: line)!.upperBound).trimmingCharacters(in: .whitespaces)
return Object(name: name, value: value)
}
return nil
}
private static func getArrayValue(line: String) -> String? {
guard line.first == "-" else {
return nil
}
return line.dropFirst().trimmingCharacters(in: .whitespaces)
}
private static func getArrayObject(line: String) -> Object? {
guard let value = getArrayValue(line: line) else {
return nil
}
return getObject(line: value)
}
}
//
// ImageInfo.swift
//
//
// Created by Sergey Balalaev on 03.04.2024.
//
import Foundation
import AppKit
struct AssetContents: Decodable {
let images: [Image]
struct Image: Decodable {
let filename: String?
let scale: String?
}
}
struct FolderContents: Decodable {
let properties: Properties?
struct Properties: Decodable {
let isNamespace: Bool
enum CodingKeys: String, CodingKey {
case isNamespace = "provides-namespace"
}
}
}
func load<T: Decodable>(_ type: T.Type, dir: String, for folder: String) -> T? {
let contentsPath = dir + folder + "/Contents.json"
guard let contentsData = NSData(contentsOfFile: contentsPath) as? Data else {
return nil
}
return try? JSONDecoder().decode(type, from: contentsData)
}
let imagesetExtension = ".imageset"
let appIconExtension = ".appiconset"
let assetExtension = ".xcassets"
public class ImageInfo {
struct File {
// needs concatinate with ImageInfo.dir
let path: String
// if nil that vector-universal
let scale: Int?
init(path: String, scale: Int?) {
self.path = path
self.scale = scale
}
}
public enum ImageType: String {
case undefined
case vector
case rastor
case mixed
}
let name: String
// dir for current Asset
let dir: String
var files: [File]
var hash: String = ""
var type: ImageType = .undefined
var fileSizes: [UInt64] = []
private(set) var imageSizes: [(width: Int, height: Int)] = []
private func setAndCheckType(newType: ImageType, filePath: String){
if type != .undefined, newType != type {
printError(
filePath: filePath,
message: "The image with name '\(name)' has different types of files: \(newType) and \(type)"
)
type = .mixed
} else {
type = newType
}
}
private init(name: String, dir: String, path: String, scale: Int?) {
self.name = name
self.dir = dir
files = [File(path: path, scale: scale)]
}
static func processFound(dir: String, path: String) -> ImageInfo? {
var isAsset = false
var folderName = ""
let components = path.split(separator: "/")
for (index, component) in components.enumerated() {
if component.hasSuffix(assetExtension) {
isAsset = true
} else {
if isAsset == false { // only for asset
continue
}
if component.hasSuffix(imagesetExtension) { // it is asset
let name = (component as NSString).substring(to: component.count - imagesetExtension.count)
if let contents = load(AssetContents.self, dir: dir, for: components[0..<index + 1].joined(separator: "/")) {
let fileName = (path as NSString).lastPathComponent
let scale: Int? = contents.images.reduce(into: nil) { result, image in
if image.filename == fileName {
result = image.scale?.scale
}
}
return processFound(name: folderName + name, dir: dir, path: path, scale: scale)
} else {
printError(filePath: path, message: "Not readed scale information. Found for image '\(name)'", isWarning: true)
return processFound(name: folderName + name, dir: dir, path: path, scale: nil)
}
//break
} else if component.hasSuffix(appIconExtension) { // it is Application icon and we will ignore it
return nil
} else {
// It is folder, but way???
if let contents = load(FolderContents.self, dir: dir, for: components[0..<index + 1].joined(separator: "/")) {
if contents.properties?.isNamespace ?? false {
folderName += component + "/"
}
}
}
}
}
if !isAsset {
let name = nameOfImageFile(path: path)
return processFound(name: name.path, dir: dir, path: path, scale: name.scale)
}
return nil
}
private static func processFound(name: String, dir: String, path: String, scale: Int?) -> ImageInfo {
if let existImage = foundedImages[name] {
existImage.files.append(File(path: path, scale: scale))
return existImage
} else {
let result = ImageInfo(name: name, dir: dir, path: path, scale: scale)
foundedImages[name] = result
if isSwiftGen {
foundedSwiftGenMirrorImages[name.swiftGenKey()] = name
}
return result
}
}
private static func nameOfImageFile(path: String) -> (path: String, scale: Int) {
return pathOfImageFile(path: (path as NSString).lastPathComponent)
}
private static func pathOfImageFile(path: String) -> (path: String, scale: Int) {
var name = (path as NSString).deletingPathExtension
var scale = 1
for imageScale in allImageScales {
let scaleSuffix = "@\(imageScale)x"
if name.hasSuffix(scaleSuffix) {
name = String(name.dropLast(scaleSuffix.count))
scale = imageScale
break
}
}
return (name, scale)
}
private static func isTheSameImage(path1: String, path2: String) -> Bool {
pathOfImageFile(path: path1).path == pathOfImageFile(path: path2).path
}
private var assetPath: String? {
var result: String?
for imageFile in files {
let components = imageFile.path.split(separator: "/")
if components.isEmpty { // it just image
return nil
} else {
for component in components {
if component.hasSuffix(imagesetExtension) { // it is asset
var name = (imageFile.path as NSString).components(separatedBy: imagesetExtension).first ?? ""
name = name + imagesetExtension
if let result = result {
if name != result {
return nil
}
} else {
result = name
}
}
}
}
}
return result
}
func error(with message: String) {
for file in files {
let imageFilePath = dir + file.path
printError(filePath: imageFilePath, message: message)
guard settings.isAllFilesErrorShowing else {
break
}
}
}
func checkDuplicateByName() {
guard files.count > 1 else {
return
}
if assetPath == nil {
var isDifferentImages = false
for file in files {
if !Self.isTheSameImage(path1: files.first?.path ?? "", path2: file.path) {
isDifferentImages = true
break
}
}
if isDifferentImages {
error(with: "Duplicated image with name: '\(name)'")
}
}
}
private static let svgSearchWidthHeightRegex = try! NSRegularExpression(pattern: #"<svg.*width="(.*?)p?t?".*height="(.*?)p?t?".*>"#, options: [])
private static let svgSearchHeightWidthRegex = try! NSRegularExpression(pattern: #"<svg.*height="(.*?)p?t?".*width="(.*?)p?t?".*>"#, options: [])
func checkImageSizeAndDetectType() {
var scaledSize: (width: Int, height: Int)?
for file in files {
let imageFilePath = dir + file.path
if let image = NSImage(contentsOfFile: imageFilePath) {
let pixelSize = image.pixelSize ?? NSSize()
let size = image.size
if pixelSize.height == 0, pixelSize.width == 0 {
if size.height != 0, size.width != 0 {
setAndCheckType(newType: .vector, filePath: imageFilePath)
// it's okey just vector image
// but can problems
if let scale = file.scale {
printError(
filePath: imageFilePath,
message: "It is vector image. But it has scale = \(scale). Found for image '\(name)'",
isWarning: true
)
}
imageSizes.append((width: Int(size.width), height: Int(size.height)))
if size.width > settings.maxVectorImageSize.width || size.height > settings.maxVectorImageSize.height {
printError(
filePath: imageFilePath,
message: "The vector image has very biggest image size (\(size.width), \(size.height)). Max image size for vector is (\(settings.maxVectorImageSize.width), \(settings.maxVectorImageSize.height)). Found for image '\(name)'"
)
}
} else {
printError(filePath: imageFilePath, message: "Image has zero size. Found for image '\(name)'", isWarning: true)
}
} else {
if let scale = file.scale {
setAndCheckType(newType: .rastor, filePath: imageFilePath)
if Int(pixelSize.width) % scale != 0 || Int(pixelSize.height) % scale != 0 {
let newScaledSize: (width: Double, height: Double) = (Double(pixelSize.width) / Double(scale), Double(pixelSize.height) / Double(scale))
printError(
filePath: imageFilePath,
message: "Image has floating size from scaled images. Real size is \(pixelSize) and scale = \(scale). Please check the file, it must have integer size after apply this scale. But you actually have \(newScaledSize). Found for image '\(name)'."
)
} else {
let newScaledSize: (width: Int, height: Int) = (Int(pixelSize.width) / scale, Int(pixelSize.height) / scale)
if let scaledSize = scaledSize {
if scaledSize != newScaledSize {
printError(
filePath: imageFilePath,
message: "Image has different size for scaled group. Real size is \(pixelSize) with scale = \(scale) but expected \(NSSize(width: scaledSize.0 * scale, height: scaledSize.1 * scale)). Found for image '\(name)'"
)
}
} else {
scaledSize = newScaledSize
}
imageSizes.append(newScaledSize)
if CGFloat(newScaledSize.width) > settings.maxRastorImageSize.width || CGFloat(newScaledSize.height) > settings.maxRastorImageSize.height{
printError(
filePath: imageFilePath,
message: "The rastor image has very biggest image size (\(newScaledSize.width), \(newScaledSize.height)). Max image size for rastor is (\(settings.maxRastorImageSize.width), \(settings.maxRastorImageSize.height)). Found for image '\(name)'"
)
}
}
}
}
} else if imageFilePath.uppercased().hasSuffix("SVG") { // NSImage can not support SVG files. You can use only from Assets
setAndCheckType(newType: .vector, filePath: imageFilePath)
if let scale = file.scale {
printError(
filePath: imageFilePath,
message: "It is vector image. But it has scale = \(scale). Found for image '\(name)'",
isWarning: true
)
}
// Need parse SVG and extract width / height for checking
// examples:
// vector: <svg width="37pt" height="37pt" viewBox="0 0 37 37" >
// rastor: <svg width="50" height="50" viewBox="636,559,50,50">
if settings.isCheckingImageSize {
if let string = try? String(contentsOfFile: imageFilePath, encoding: .ascii) {
let range = NSRange(location: 0, length: string.count)
if let result = Self.svgSearchWidthHeightRegex.firstMatch(in: string, options: [], range: range) {
print("VALUE!!!")
let _ = (1...result.numberOfRanges - 1).map { index in
let value = (string as NSString).substring(with: result.range(at: index))
print("VALUE=\(value)")
}
}
} else {
printError(filePath: imageFilePath, message: "Can not parse SVG file. Found for image '\(name)'")
}
}
} else {
printError(filePath: imageFilePath, message: "That is not image. Found for image '\(name)'", isWarning: true)
}
}
if type == .vector, files.count > 1 {
printError(
filePath: files.first?.path ?? "",
message: "The vector image with name '\(name)' has \(files.count) files",
isWarning: true
)
} else if type == .rastor {
// Analysis scales with dependency on target platforms
let currentScalesDictionary : Dictionary<Int, File> = files.reduce(Dictionary<Int, File>()) { result, file in
if let scale = file.scale {
var newResult = result
newResult[scale] = file
return newResult
} else {
printError(
filePath: file.path,
message: "The rastor image with name '\(name)' has undefined scale. May be it's vector?",
isWarning: true
)
}
return result
}
let currentScales = Set<Int>(currentScalesDictionary.keys)
let extraScales = currentScales.subtracting(targetScales)
for extraScale in extraScales {
printError(
filePath: currentScalesDictionary[extraScale]?.path ?? "",
message: "The rastor image with name '\(name)' has extra scale=\(extraScale) for current platforms target (\(settings.targetPlatforms)).",
isWarning: true
)
}
let missingScales = targetScales.subtracting(currentScales)
if missingScales.count > 0 {
printError(
filePath: files.first?.path ?? "",
message: "The rastor image with name '\(name)' has missing scale=\(missingScales). You need add images with this scales for correct showing at selected target platforms = \(settings.targetPlatforms).",
isWarning: true
)
}
}
}
func calculateData() -> Data? {
var maxScale = 0
var result: Data?
for file in files {
let imageFilePath = dir + file.path
if let image = NSImage(contentsOfFile: imageFilePath), let pixelSize = image.pixelSize {
let size = image.size
if pixelSize.height == 0, pixelSize.width == 0 {
if size.height != 0, size.width != 0 {
// it's okey just vector image
var imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
let cgImage = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
if let data = cgImage?.png {
result = data
maxScale = 1
}
}
} else {
if let scale = file.scale {
// calculate hash
if maxScale < scale {
var imageRect = CGRect(
x: 0,
y: 0,
width: Int(pixelSize.width) / scale,
height: Int(pixelSize.height) / scale
)
let cgImage = image.cgImage(forProposedRect: &imageRect, context: nil, hints: nil)
if let data = cgImage?.png {
result = data
maxScale = scale
}
}
}
}
}
}
return result
}
}
//
// Settings.swift
//
//
// Created by Sergey Balalaev on 02.04.2024.
//
import Foundation
public struct Settings {
/// For enable or disable this script
public internal(set) var isEnabled = true
private(set) var dir: String = defaultDir
/// Multipath to folders with images you actually use in your project. For Example ["/YouProject/Resources/Images", "/OtherProject"]
public internal(set) var relativeImagesPaths: [String] = []
/// Multipath of the sources folders which will used in searching for images you actually use in your project. For Example ["/YouProject/Source", "/OtherProject"]
public internal(set) var relativeSourcePaths: [String] = []
/// Using images type from code. If you use custom you need define regex pattern
public enum UsingType {
case swiftUI
case uiKit
case uiKitLiteral
case swiftGen(enumName: String = "Asset")
case custom(pattern: String, isSwiftGen: Bool)
}
/// you can use many types of images usage
public internal(set) var usingTypes: [UsingType] = [
.swiftGen(),
.swiftUI,
.uiKit,
.uiKitLiteral
]
/// Patterns of checking of the image name with filter
public enum CheckingNameType {
case firstUpperCase(message: String = "Name should start with uppercase", filter: ImageFilter?)
case camelCase(message: String = "Camel case support only", filter: ImageFilter?)
case sneak_case (message: String = "Sneak case support only", filter: ImageFilter?)
case kebab_case (message: String = "Kebab case support only", filter: ImageFilter?)
case custom (pattern: String, message: String = "Custom name checking", filter: ImageFilter?)
}
/// you can check image name with a set of patterns
public internal(set) var checkingNameTypes: [CheckingNameType] = []
/// If you want to exclude unused image from checking, you can define they this
public internal(set) var ignoredUnusedImages: Set<String> = [ ]
public internal(set) var ignoredUndefinedImages: Set<String> = [ ]
public internal(set) var rastorExtensions = Set<String>(["png", "jpg", "jpeg"].map{$0.uppercased()})
public internal(set) var vectorExtensions = Set<String>(["pdf", "svg"].map{$0.uppercased()})
public internal(set) var sourcesExtensions = Set<String>(["swift", "mm", "m"].map{$0.uppercased()})
public internal(set) var resourcesExtensions = Set<String>(["storyboard", "xib"].map{$0.uppercased()})
// If you wan't show double errors/warnings for all files of an image change this to false
public internal(set) var isAllFilesErrorShowing = false
// Maximum size of Vector files in bytes.
public internal(set) var maxVectorFileSize: UInt64 = 20_000
// Maximum size of Vector images in pixels.
public internal(set) var maxVectorImageSize: CGSize = CGSize(width: 100, height: 100)
// Maximum size of Rastor files in bytes.
public internal(set) var maxRastorFileSize: UInt64 = 200_000
// Maximum size of Rastor images in pixels.
public internal(set) var maxRastorImageSize: CGSize = CGSize(width: 1000, height: 1000)
public internal(set) var isCheckingFileSize = true
public internal(set) var isCheckingImageSize = true
public internal(set) var isCheckingPdfVector = true
public internal(set) var isCheckingSvgVector = true
public internal(set) var isCheckingScaleSize = true
public internal(set) var isCheckingDuplicatedByName = true
public internal(set) var isCheckingDuplicatedByContent = true
/// Your project should compile for one or more platform. This need for detect quality of images.
public enum TargetPlatform {
case iOS