Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check missing and unused color assets #10

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions Classes/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Foundation
// Configure me \o/
var sourcePathOption:String? = nil
var assetCatalogPathOption:String? = nil
var colorAssetCatalogPathOption:String? = nil
let ignoredUnusedNames = [String]()

for (index, arg) in CommandLine.arguments.enumerated() {
Expand All @@ -13,6 +14,9 @@ for (index, arg) in CommandLine.arguments.enumerated() {
sourcePathOption = arg
case 2:
assetCatalogPathOption = arg
colorAssetCatalogPathOption = arg
case 3:
colorAssetCatalogPathOption = arg
default:
break
}
Expand All @@ -28,6 +32,11 @@ guard let assetCatalogAbsolutePath = assetCatalogPathOption else {
exit(0)
}

guard let colorAssetCatalogAbsolutePath = colorAssetCatalogPathOption else {
print("AssetChecker:: error: Color Asset Catalog path was missing!")
exit(0)
}

print("Searching sources in \(sourcePath) for assets in \(assetCatalogAbsolutePath)")

/* Put here the asset generating false positives,
Expand Down Expand Up @@ -133,3 +142,77 @@ broken.forEach { print("\(assetCatalogAbsolutePath):: error: [Asset Missing] \($
if broken.count > 0 {
exit(1)
}


// MARK: Colors
func listColorAssets() -> [String] {
let extensionName = "colorset"
let enumerator = FileManager.default.enumerator(atPath: colorAssetCatalogAbsolutePath)
return elementsInEnumerator(enumerator)
.filter { $0.hasSuffix(extensionName) } // Is Asset
.map { $0.replacingOccurrences(of: ".\(extensionName)", with: "") } // Remove extension
.map { $0.components(separatedBy: "/").last ?? $0 } // Remove folder path
}

func colorStrings(inStringFile: String) -> [String] {
var localizedStrings = [String]()
let namePattern = "([\\w-]+)"
let patterns = [
"#colorLiteral\\(resourceName: \"\(namePattern)\"\\)", // Image Literal
"UIColor\\(named:\\s*\"\(namePattern)\"\\)", // Default UIImage call (Swift)
"UIColor colorNamed:\\s*\\@\"\(namePattern)\"", // Default UIImage call
"\\<namedColor name=\"\(namePattern)\".*", // Storyboard resources
"R.color.\(namePattern)\\(\\)" //R.swift support
]
for p in patterns {
let regex = try? NSRegularExpression(pattern: p, options: [])
let range = NSRange(location:0, length:(inStringFile as NSString).length)
regex?.enumerateMatches(in: inStringFile,options: [], range: range) { result, _, _ in
if let r = result {
let value = (inStringFile as NSString).substring(with:r.range(at: 1))
localizedStrings.append(value)
}
}
}
return localizedStrings
}

func listUsedColorAssetLiterals() -> [String] {
let enumerator = FileManager.default.enumerator(atPath:sourcePath)
print(sourcePath)

#if swift(>=4.1)
return elementsInEnumerator(enumerator)
.filter { $0.hasSuffix(".m") || $0.hasSuffix(".swift") || $0.hasSuffix(".xib") || $0.hasSuffix(".storyboard") } // Only Swift and Obj-C files
.map { "\(sourcePath)/\($0)" } // Build file paths
.map { try? String(contentsOfFile: $0, encoding: .utf8)} // Get file contents
.compactMap{$0} // Remove nil entries
.map(colorStrings) // Find localizedStrings ocurrences
.flatMap{$0} // Flatten
#else
return elementsInEnumerator(enumerator)
.filter { $0.hasSuffix(".m") || $0.hasSuffix(".swift") || $0.hasSuffix(".xib") || $0.hasSuffix(".storyboard") } // Only Swift and Obj-C files
.map { "\(sourcePath)/\($0)" } // Build file paths
.map { try? String(contentsOfFile: $0, encoding: .utf8)} // Get file contents
.flatMap{$0} // Remove nil entries
.map(colorStrings) // Find localizedStrings ocurrences
.flatMap{$0} // Flatten
#endif
}

print("Searching colors in \(sourcePath) for color assets in \(colorAssetCatalogAbsolutePath)")

let colors = Set(listColorAssets())
let usedColors = Set(listUsedColorAssetLiterals())

// Generate Warnings for Unused Assets
let unusedColors = colors.subtracting(usedColors)
unusedColors.forEach { print("\(colorAssetCatalogAbsolutePath):: warning: [Color Unused] \($0)") }

// Generate Error for broken Assets
let brokenColors = usedColors.subtracting(colors)
brokenColors.forEach { print("\(assetCatalogAbsolutePath):: error: [Color Missing] \($0)") }

if brokenColors.count > 0 {
exit(1)
}
2 changes: 1 addition & 1 deletion Example/AssetChecker.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "${PODS_ROOT}/AssetChecker/run --catalog ${SRCROOT}/Resource/Images.xcassets";
shellScript = "${PODS_ROOT}/AssetChecker/run --catalog ${SRCROOT}/AssetChecker/Images.xcassets --colors ${SRCROOT}/AssetChecker/Images.xcassets\n";
};
CD3F94CDB64297E52FBE5D36 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
Expand Down
22 changes: 14 additions & 8 deletions Example/AssetChecker/Base.lproj/Main.storyboard
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13771" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="vXZ-lx-hvc">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="17701" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="vXZ-lx-hvc">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13772"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="17703"/>
<capability name="Named colors" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
Expand All @@ -22,13 +21,14 @@
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
<subviews>
<stackView opaque="NO" contentMode="scaleToFill" axis="vertical" translatesAutoresizingMaskIntoConstraints="NO" id="dcL-fK-p7R">
<rect key="frame" x="30" y="50" width="315" height="587"/>
<rect key="frame" x="30" y="30" width="315" height="607"/>
<subviews>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" ambiguous="YES" translatesAutoresizingMaskIntoConstraints="NO" id="vXm-mP-bVU">
<rect key="frame" x="0.0" y="0.0" width="315" height="128"/>
<rect key="frame" x="0.0" y="0.0" width="315" height="148"/>
</imageView>
<imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" ambiguous="YES" translatesAutoresizingMaskIntoConstraints="NO" id="vDD-em-TGY">
<rect key="frame" x="0.0" y="128" width="315" height="459"/>
<rect key="frame" x="0.0" y="148" width="315" height="459"/>
<color key="backgroundColor" name="DeletedColor"/>
</imageView>
</subviews>
</stackView>
Expand All @@ -44,6 +44,12 @@
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="x5A-6p-PRh" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-58" y="118"/>
</scene>
</scenes>
<resources>
<namedColor name="DeletedColor">
<color red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</namedColor>
</resources>
</document>
6 changes: 6 additions & 0 deletions Example/AssetChecker/Images.xcassets/Contents.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"colors" : [
{
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "1.000",
"green" : "1.000",
"red" : "1.000"
}
},
"idiom" : "universal"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"color" : {
"color-space" : "srgb",
"components" : {
"alpha" : "1.000",
"blue" : "1.000",
"green" : "1.000",
"red" : "1.000"
}
},
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
7 changes: 6 additions & 1 deletion run
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ swiftFile="${DIR}/Classes/main.swift"

SOURCE=$SRCROOT
CATALOG=""
COLORS_CATALOG=""

while [[ $# > 0 ]]
do
Expand All @@ -22,6 +23,10 @@ case $key in
CATALOG="$2"
shift # past argument
;;
--colors)
COLORS_CATALOG="$2"
shift # past argument
;;
*)

# unknown option
Expand All @@ -30,6 +35,6 @@ esac
shift # past argument or value
done

cmd="$swiftFile $SOURCE $CATALOG"
cmd="$swiftFile $SOURCE $CATALOG $COLORS_CATALOG"
echo $cmd
$cmd