7 Commits

Author SHA1 Message Date
cdricms
887d4b3727 Added LaunchAtLogin functionality 2024-07-10 17:52:18 +02:00
cdricms
5cfd971f57 Release of version 0.1.2-beta 2024-07-10 11:59:30 +02:00
cdricms
675f4ee89b Fixed padding on components 2024-07-10 11:49:48 +02:00
cdricms
4c9665a41b Update button + some bug fixes 2024-07-10 11:40:17 +02:00
cdricms
253f550212 Added quit button, and fixed WindowGroup showing up 2024-07-09 22:24:41 +02:00
cdricms
dc99548d07 Formatting 2024-07-09 20:35:00 +02:00
cdricms
6b3b26e4bc Formatting 2024-07-09 20:30:04 +02:00
16 changed files with 757 additions and 515 deletions

2
.gitignore vendored
View File

@@ -97,4 +97,4 @@ fastlane/test_output
# https://github.com/johnno1962/injectionforxcode
iOSInjectionProject/
.DS_Store

69
.swift-format Normal file
View File

@@ -0,0 +1,69 @@
{
"fileScopedDeclarationPrivacy" : {
"accessLevel" : "private"
},
"indentation" : {
"tabs" : 1
},
"indentConditionalCompilationBlocks" : true,
"indentSwitchCaseLabels" : false,
"lineBreakAroundMultilineExpressionChainComponents" : false,
"lineBreakBeforeControlFlowKeywords" : false,
"lineBreakBeforeEachArgument" : false,
"lineBreakBeforeEachGenericRequirement" : false,
"lineLength" : 80,
"maximumBlankLines" : 1,
"multiElementCollectionTrailingCommas" : true,
"noAssignmentInExpressions" : {
"allowedFunctions" : [
"XCTAssertNoThrow"
]
},
"prioritizeKeepingFunctionOutputTogether" : false,
"respectsExistingLineBreaks" : true,
"rules" : {
"AllPublicDeclarationsHaveDocumentation" : false,
"AlwaysUseLiteralForEmptyCollectionInit" : false,
"AlwaysUseLowerCamelCase" : true,
"AmbiguousTrailingClosureOverload" : true,
"BeginDocumentationCommentWithOneLineSummary" : false,
"DoNotUseSemicolons" : true,
"DontRepeatTypeInStaticProperties" : true,
"FileScopedDeclarationPrivacy" : true,
"FullyIndirectEnum" : true,
"GroupNumericLiterals" : true,
"IdentifiersMustBeASCII" : true,
"NeverForceUnwrap" : false,
"NeverUseForceTry" : false,
"NeverUseImplicitlyUnwrappedOptionals" : false,
"NoAccessLevelOnExtensionDeclaration" : true,
"NoAssignmentInExpressions" : true,
"NoBlockComments" : true,
"NoCasesWithOnlyFallthrough" : true,
"NoEmptyTrailingClosureParentheses" : true,
"NoLabelsInCasePatterns" : true,
"NoLeadingUnderscores" : false,
"NoParensAroundConditions" : true,
"NoPlaygroundLiterals" : true,
"NoVoidReturnOnFunctionSignature" : true,
"OmitExplicitReturns" : false,
"OneCasePerLine" : true,
"OneVariableDeclarationPerLine" : true,
"OnlyOneTrailingClosureArgument" : true,
"OrderedImports" : true,
"ReplaceForEachWithForLoop" : true,
"ReturnVoidInsteadOfEmptyTuple" : true,
"TypeNamesShouldBeCapitalized" : true,
"UseEarlyExits" : false,
"UseLetInEveryBoundCaseVariable" : true,
"UseShorthandTypeNames" : true,
"UseSingleLinePropertyGetter" : true,
"UseSynthesizedInitializer" : true,
"UseTripleSlashForDocumentationComments" : true,
"UseWhereClausesInForLoops" : false,
"ValidateDocumentationComments" : false
},
"spacesAroundRangeFormationOperators" : false,
"tabWidth" : 4,
"version" : 1
}

View File

@@ -12,6 +12,8 @@
9E6C730C2C3D796D0056ADDC /* DownloadButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E6C730B2C3D796D0056ADDC /* DownloadButton.swift */; };
9E6C730E2C3DB16F0056ADDC /* UninstallButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E6C730D2C3DB16F0056ADDC /* UninstallButton.swift */; };
9E6C73112C3DB5940056ADDC /* CaskDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E6C73102C3DB5940056ADDC /* CaskDetailView.swift */; };
9E6C73182C3E853E0056ADDC /* UpdateButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E6C73172C3E853E0056ADDC /* UpdateButton.swift */; };
9E7ADB5A2C3EE41F00F2B8CA /* LaunchAtLogin in Frameworks */ = {isa = PBXBuildFile; productRef = 9E7ADB592C3EE41F00F2B8CA /* LaunchAtLogin */; };
9E8CE5362C3C545600A39146 /* BrewerApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E8CE5352C3C545600A39146 /* BrewerApp.swift */; };
9E8CE5382C3C545600A39146 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E8CE5372C3C545600A39146 /* ContentView.swift */; };
9E8CE53A2C3C545700A39146 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9E8CE5392C3C545700A39146 /* Assets.xcassets */; };
@@ -45,6 +47,7 @@
9E6C730B2C3D796D0056ADDC /* DownloadButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloadButton.swift; sourceTree = "<group>"; };
9E6C730D2C3DB16F0056ADDC /* UninstallButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UninstallButton.swift; sourceTree = "<group>"; };
9E6C73102C3DB5940056ADDC /* CaskDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CaskDetailView.swift; sourceTree = "<group>"; };
9E6C73172C3E853E0056ADDC /* UpdateButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateButton.swift; sourceTree = "<group>"; };
9E8CE5322C3C545600A39146 /* Brewer.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Brewer.app; sourceTree = BUILT_PRODUCTS_DIR; };
9E8CE5352C3C545600A39146 /* BrewerApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrewerApp.swift; sourceTree = "<group>"; };
9E8CE5372C3C545600A39146 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
@@ -64,6 +67,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
9E7ADB5A2C3EE41F00F2B8CA /* LaunchAtLogin in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -88,6 +92,7 @@
isa = PBXGroup;
children = (
9E6C730B2C3D796D0056ADDC /* DownloadButton.swift */,
9E6C73172C3E853E0056ADDC /* UpdateButton.swift */,
9E6C730D2C3DB16F0056ADDC /* UninstallButton.swift */,
);
path = Components;
@@ -187,6 +192,9 @@
dependencies = (
);
name = Brewer;
packageProductDependencies = (
9E7ADB592C3EE41F00F2B8CA /* LaunchAtLogin */,
);
productName = Brewer;
productReference = 9E8CE5322C3C545600A39146 /* Brewer.app */;
productType = "com.apple.product-type.application";
@@ -259,6 +267,9 @@
Base,
);
mainGroup = 9E8CE5292C3C545600A39146;
packageReferences = (
9E98BE4E2C3EE353006ED274 /* XCRemoteSwiftPackageReference "LaunchAtLogin-Modern" */,
);
productRefGroup = 9E8CE5332C3C545600A39146 /* Products */;
projectDirPath = "";
projectRoot = "";
@@ -304,6 +315,7 @@
9E6C73072C3D5E570056ADDC /* SearchView.swift in Sources */,
9E6C730C2C3D796D0056ADDC /* DownloadButton.swift in Sources */,
9E8CE5382C3C545600A39146 /* ContentView.swift in Sources */,
9E6C73182C3E853E0056ADDC /* UpdateButton.swift in Sources */,
9E6C730E2C3DB16F0056ADDC /* UninstallButton.swift in Sources */,
9E8CE5622C3C5A6A00A39146 /* Homebrew.swift in Sources */,
9E6C73092C3D5E950056ADDC /* InstalledView.swift in Sources */,
@@ -469,21 +481,24 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = Brewer/Brewer.entitlements;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "-";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = "0.1.3-beta";
DEVELOPMENT_ASSET_PATHS = "\"Brewer/Preview Content\"";
DEVELOPMENT_TEAM = 96S93Z7LTG;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = Brewer;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities";
INFOPLIST_KEY_LSUIElement = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MARKETING_VERSION = 1.0;
MARKETING_VERSION = "0.1.3-beta";
PRODUCT_BUNDLE_IDENTIFIER = dev.cems.Brewer;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -497,21 +512,24 @@
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = Brewer/Brewer.entitlements;
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "-";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = "0.1.3-beta";
DEVELOPMENT_ASSET_PATHS = "\"Brewer/Preview Content\"";
DEVELOPMENT_TEAM = 96S93Z7LTG;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_PREVIEWS = YES;
GENERATE_INFOPLIST_FILE = YES;
INFOPLIST_KEY_CFBundleDisplayName = Brewer;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.utilities";
INFOPLIST_KEY_LSUIElement = YES;
INFOPLIST_KEY_NSHumanReadableCopyright = "";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MARKETING_VERSION = 1.0;
MARKETING_VERSION = "0.1.3-beta";
PRODUCT_BUNDLE_IDENTIFIER = dev.cems.Brewer;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -631,6 +649,25 @@
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
9E98BE4E2C3EE353006ED274 /* XCRemoteSwiftPackageReference "LaunchAtLogin-Modern" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/sindresorhus/LaunchAtLogin-Modern";
requirement = {
branch = main;
kind = branch;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
9E7ADB592C3EE41F00F2B8CA /* LaunchAtLogin */ = {
isa = XCSwiftPackageProductDependency;
package = 9E98BE4E2C3EE353006ED274 /* XCRemoteSwiftPackageReference "LaunchAtLogin-Modern" */;
productName = LaunchAtLogin;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 9E8CE52A2C3C545600A39146 /* Project object */;
}

View File

@@ -0,0 +1,15 @@
{
"originHash" : "aae61040c30e63b9cf0f5455365680cfeabef0aac829c0941d4d6f6180010fc9",
"pins" : [
{
"identity" : "launchatlogin-modern",
"kind" : "remoteSourceControl",
"location" : "https://github.com/sindresorhus/LaunchAtLogin-Modern",
"state" : {
"branch" : "main",
"revision" : "a04ec1c363be3627734f6dad757d82f5d4fa8fcc"
}
}
],
"version" : 3
}

View File

@@ -5,38 +5,60 @@
// Created by Cédric MAS on 08/07/2024.
//
import LaunchAtLogin
import SwiftUI
@main
struct BrewerApp: App {
@AppStorage("isUpToDate") var isUpToDate: Bool = true
init() {
do {
let res = try shell("/opt/homebrew/bin/brew outdated --greedy-latest -g | wc -l")
if let number = Int(res.trimmingCharacters(in: .whitespacesAndNewlines)), number > 0 {
isUpToDate = false
}
} catch {
print(error.localizedDescription)
}
}
@AppStorage("isUpToDate") var isUpToDate: Bool = true
init() {
do {
let res = try shell(
"/opt/homebrew/bin/brew outdated --greedy-latest -g | wc -l")
if let number = Int(
res.trimmingCharacters(in: .whitespacesAndNewlines)), number > 0
{
print(number)
isUpToDate = false
}
} catch {
print(error.localizedDescription)
}
}
var body: some Scene {
WindowGroup {
EmptyView()
}
MenuBarExtra {
ContentView().padding()
} label: {
if isUpToDate {
Label("Brewer", systemImage: "sparkle.magnifyingglass")
} else {
Label("Brewer", systemImage: "sparkle.magnifyingglass")
.symbolRenderingMode(.palette)
.foregroundStyle(.orange)
}
}
.menuBarExtraStyle(.window)
}
var body: some Scene {
MenuBarExtra {
VStack(spacing: 0) {
ContentView()
Form {
HStack {
LaunchAtLogin.Toggle()
Button {
NSApplication.shared.terminate(self)
} label: {
Label("Quit", systemImage: "x")
.symbolRenderingMode(.palette)
.symbolVariant(.circle)
.symbolVariant(.fill)
.foregroundStyle(.white, .red)
}
.frame(maxWidth: .infinity, alignment: .trailing)
}
}
}.padding()
} label: {
if isUpToDate {
Label("Brewer", systemImage: "sparkle.magnifyingglass")
} else {
Label("Brewer", systemImage: "sparkle.magnifyingglass")
.symbolRenderingMode(.palette)
.foregroundStyle(.orange)
}
}
.menuBarExtraStyle(.window)
WindowGroup {
EmptyView()
}
}
}

View File

@@ -8,31 +8,32 @@
import SwiftUI
struct CaskDetailView: View {
var cask: Cask
@Bindable var brewListing: Homebrew
var body: some View {
NavigationStack {
VStack {
Text("Identifier: \(cask.fullToken)")
Text("Version: \(cask.version)")
}
.navigationTitle(cask.name.first ?? cask.fullToken)
.toolbar {
ToolbarItem(placement: .primaryAction) {
if cask.installed == nil {
DownloadButton(name: cask.fullToken, isCask: true)
} else if cask.outdated {
Button("Update") {
var cask: Cask
@Bindable var brewListing: Homebrew
var body: some View {
NavigationStack {
VStack {
Text("Identifier: \(cask.fullToken)")
Text("Version: \(cask.version)")
}
.navigationTitle(cask.name.first ?? cask.fullToken)
.toolbar {
ToolbarItem(placement: .primaryAction) {
if cask.installed == nil {
DownloadButton(name: cask.fullToken, isCask: true)
} else if cask.outdated {
Button("Update") {
}
}
}
if cask.installed != nil {
ToolbarItem(placement: .primaryAction) {
UninstallButton(name: cask.fullToken, brewListing: brewListing)
}
}
}
}
}
}
}
}
if cask.installed != nil {
ToolbarItem(placement: .primaryAction) {
UninstallButton(
name: cask.fullToken, brewListing: brewListing)
}
}
}
}
}
}

View File

@@ -8,46 +8,46 @@
import SwiftUI
struct DownloadButton: View {
let name: String
var isCask: Bool = false
@State private var brew = Homebrew()
@State private var downloaded = false
let name: String
var isCask: Bool = false
@State private var brew = Homebrew()
@State private var downloaded = false
var body: some View {
VStack {
if downloaded {
Image(systemName: "checkmark")
.symbolRenderingMode(.palette)
.symbolVariant(.circle)
.symbolVariant(.fill)
.foregroundStyle(.white, .green)
} else if brew.isLoading {
ProgressView()
.controlSize(.small)
} else if brew.errorMessage != nil {
Image(systemName: "x")
.symbolRenderingMode(.palette)
.symbolVariant(.circle)
.symbolVariant(.fill)
.foregroundStyle(.white, .red)
} else {
Button("Get") {
Task {
downloaded = await brew.install(name, isCask: isCask)
}
}
.buttonBorderShape(.capsule)
.buttonStyle(.borderedProminent)
}
}
.onAppear {
Task {
downloaded = await brew.isDownloaded(name)
}
}
}
var body: some View {
VStack {
if downloaded {
Image(systemName: "checkmark")
.symbolRenderingMode(.palette)
.symbolVariant(.circle)
.symbolVariant(.fill)
.foregroundStyle(.white, .green)
} else if brew.isLoading {
ProgressView()
.controlSize(.small)
} else if brew.errorMessage != nil {
Image(systemName: "x")
.symbolRenderingMode(.palette)
.symbolVariant(.circle)
.symbolVariant(.fill)
.foregroundStyle(.white, .red)
} else {
Button("Get") {
Task {
downloaded = await brew.install(name, isCask: isCask)
}
}
.buttonBorderShape(.capsule)
.buttonStyle(.borderedProminent)
}
}
.onAppear {
Task {
downloaded = await brew.isDownloaded(name)
}
}
}
}
#Preview {
DownloadButton(name: "firefox")
DownloadButton(name: "firefox")
}

View File

@@ -8,38 +8,38 @@
import SwiftUI
struct UninstallButton: View {
let name: String
@State private var brew = Homebrew()
@State private var uninstalled = false
@Bindable var brewListing: Homebrew
var body: some View {
VStack {
if uninstalled {
EmptyView()
} else if brew.isLoading {
ProgressView()
.controlSize(.small)
} else if brew.errorMessage != nil {
Image(systemName: "x")
.symbolRenderingMode(.palette)
.symbolVariant(.circle)
.symbolVariant(.fill)
.foregroundStyle(.white, .red)
} else {
Button("Uninstall", role: .destructive) {
Task {
uninstalled = await brew.uninstall(name)
brewListing.getInstalled()
}
}
.buttonBorderShape(.capsule)
.buttonStyle(.borderedProminent)
}
}
.onAppear {
Task {
uninstalled = await brew.isDownloaded(name)
}
}
}
let name: String
@State private var brew = Homebrew()
@State private var uninstalled = false
@Bindable var brewListing: Homebrew
var body: some View {
VStack {
if uninstalled {
EmptyView()
} else if brew.isLoading {
ProgressView()
.controlSize(.small)
} else if brew.errorMessage != nil {
Image(systemName: "x")
.symbolRenderingMode(.palette)
.symbolVariant(.circle)
.symbolVariant(.fill)
.foregroundStyle(.white, .red)
} else {
Button("Uninstall", role: .destructive) {
Task {
uninstalled = await brew.uninstall(name)
brewListing.getInstalled()
}
}
.buttonBorderShape(.capsule)
.buttonStyle(.borderedProminent)
}
}
.onAppear {
Task {
uninstalled = await brew.isDownloaded(name)
}
}
}
}

View File

@@ -0,0 +1,61 @@
//
// UpdateButton.swift
// Brewer
//
// Created by Cédric MAS on 10/07/2024.
//
import SwiftUI
struct UpdateButton: View {
let name: String
@State private var brew = Homebrew()
@State private var newInfo = Homebrew()
private var updated: String? {
if let cask = newInfo.data?.casks.first(where: { $0.fullToken == name }
), !cask.outdated {
return cask.version
}
if let formulae = newInfo.data?.formulae.first(where: {
$0.fullName == name
}), !formulae.outdated {
return formulae.versions.stable
}
return nil
}
var body: some View {
if let newVersion = updated {
Text("Updated: \(newVersion)")
} else if brew.isLoading {
ProgressView()
.controlSize(.small)
} else if brew.errorMessage != nil {
Image(systemName: "x")
.symbolRenderingMode(.palette)
.symbolVariant(.circle)
.symbolVariant(.fill)
.foregroundStyle(.white, .red)
} else {
Button {
Task {
await brew.update(name)
newInfo.getInfo(on: name)
}
} label: {
Label(
"Update",
systemImage:
"arrow.counterclockwise"
)
.symbolRenderingMode(.palette)
.symbolVariant(.circle)
.symbolVariant(.fill)
.foregroundStyle(
.white, .orange)
}
}
}
}

View File

@@ -8,29 +8,32 @@
import SwiftUI
enum SegementedSelection: String, CaseIterable {
case search = "Search"
case installed = "Installed"
case search = "Search"
case installed = "Installed"
}
struct ContentView: View {
@State private var segmentedSelection: SegementedSelection = .search
var body: some View {
NavigationStack {
Picker("", selection: $segmentedSelection) {
ForEach(SegementedSelection.allCases, id: \.self) { sel in
Text(sel.rawValue).tag(sel)
}
}.pickerStyle(.segmented)
switch segmentedSelection {
case .search:
SearchView()
case .installed:
InstalledView()
}
}
}
@State private var segmentedSelection: SegementedSelection = .search
var body: some View {
NavigationStack {
VStack {
Picker("", selection: $segmentedSelection) {
ForEach(SegementedSelection.allCases, id: \.self) { sel in
Text(sel.rawValue).tag(sel)
}
}.pickerStyle(.segmented)
.padding(.leading, -8)
switch segmentedSelection {
case .search:
SearchView()
case .installed:
InstalledView()
}
}
}
}
}
#Preview {
ContentView()
ContentView()
}

View File

@@ -8,101 +8,99 @@
import SwiftUI
struct InstalledView: View {
@State private var brew = Homebrew()
var body: some View {
VStack {
if brew.isLoading {
ProgressView("Loading...")
} else if let data = brew.data {
List {
if !data.casks.isEmpty {
Section {
ForEach(data.casks, id: \.fullToken) { cask in
NavigationLink {
CaskDetailView(cask: cask, brewListing: brew)
} label: {
HStack {
Text(cask.name.first ?? cask.fullToken)
Spacer()
if cask.outdated {
Button {
@State private var brew = Homebrew()
var body: some View {
VStack {
if brew.isLoading {
ProgressView("Loading...")
} else if let data = brew.data {
List {
if !data.casks.isEmpty {
Section {
ForEach(data.casks, id: \.fullToken) { cask in
NavigationLink {
CaskDetailView(
cask: cask, brewListing: brew)
} label: {
HStack {
Text(cask.name.first ?? cask.fullToken)
Spacer()
if cask.outdated {
UpdateButton(name: cask.fullToken)
} else {
Text(cask.version)
}
}
.contextMenu {
UninstallButton(
name: cask.fullToken,
brewListing: brew)
}
}
}
} header: {
HStack {
Text("Casks")
Spacer()
Text("\(data.casks.count) installed")
}
}
}
} label: {
Label("Update", systemImage: "arrow.counterclockwise.circle.fill")
.symbolRenderingMode(.palette)
.foregroundStyle(.white, .orange)
}
} else {
Text(cask.version)
}
}
.contextMenu {
UninstallButton(name: cask.fullToken, brewListing: brew)
}
}
}
} header: {
HStack {
Text("Casks")
Spacer()
Text("\(data.casks.count) installed")
}
}
}
if !data.formulae.isEmpty {
Section {
ForEach(data.formulae, id: \.fullName) { formulae in
HStack {
Text(formulae.fullName)
Spacer()
if formulae.outdated {
UpdateButton(name: formulae.fullName)
} else {
Text(formulae.versions.stable)
}
}
.contextMenu {
UninstallButton(
name: formulae.fullName,
brewListing: brew)
}
}
} header: {
HStack {
Text("Formulae")
Spacer()
Text("\(data.formulae.count) installed")
}
}
}
}
.listStyle(.inset(alternatesRowBackgrounds: true))
let areOutdated =
data.casks.filter(\.outdated).count
+ data.formulae.filter(\.outdated).count
let _ = UserDefaults.standard.set(
!(areOutdated > 0), forKey: "isUpToDate")
if areOutdated > 0 {
Button {
if !data.formulae.isEmpty {
Section {
ForEach(data.formulae, id: \.fullName) { formulae in
HStack {
Text(formulae.fullName)
Spacer()
if formulae.outdated {
Button {
} label: {
Label("Update", systemImage: "arrow.counterclockwise.circle.fill")
.symbolRenderingMode(.palette)
.foregroundStyle(.white, .orange)
}
} else {
Text(formulae.versions.stable)
}
}
.contextMenu {
UninstallButton(name: formulae.fullName, brewListing: brew)
}
}
} header: {
HStack {
Text("Formulae")
Spacer()
Text("\(data.formulae.count) installed")
}
}
}
}
.listStyle(.inset(alternatesRowBackgrounds: true))
let areOutdated = data.casks.map(\.outdated).count + data.formulae.map(\.outdated).count
let _ = UserDefaults.standard.set(!(areOutdated > 0), forKey: "isUpToDate")
if areOutdated > 0 {
Button {
} label: {
Label("Update all", systemImage: "arrow.counterclockwise.circle.fill")
}
.buttonStyle(.borderedProminent)
.tint(.orange)
}
} else if let error = brew.errorMessage {
Text(error)
.foregroundStyle(.red)
}
}.task {
brew.getInstalled()
}
}
} label: {
Label(
"Update all",
systemImage: "arrow.counterclockwise.circle.fill")
}
.buttonStyle(.borderedProminent)
.tint(.orange)
}
} else if let error = brew.errorMessage {
Text(error)
.foregroundStyle(.red)
}
}.task {
brew.getInstalled()
}
}
}
#Preview {
InstalledView()
InstalledView()
}

View File

@@ -8,207 +8,241 @@
import Foundation
enum ShellError: Error {
case emptyOutput
case emptyOutput
}
@discardableResult
func shell(_ command: String) throws -> String {
let task = Process()
task.executableURL = URL(filePath: "/bin/bash")
task.arguments = ["-c", command]
let task = Process()
task.executableURL = URL(filePath: "/bin/bash")
task.arguments = ["-c", command]
let pipe = Pipe()
task.standardError = pipe
task.standardOutput = pipe
let pipe = Pipe()
task.standardError = pipe
task.standardOutput = pipe
try task.run()
if let data = try pipe.fileHandleForReading.readToEnd(),
let output = String(data: data, encoding: .utf8)
{
return output
}
try task.run()
if let data = try pipe.fileHandleForReading.readToEnd(),
let output = String(data: data, encoding: .utf8)
{
return output
}
throw ShellError.emptyOutput
throw ShellError.emptyOutput
}
struct Cask: Codable {
let token: String
let fullToken: String
let tap: String
let name: [String]
let desc: String
let homepage: String
let url: String
let version: String
let installed: String?
let outdated: Bool
let token: String
let fullToken: String
let tap: String
let name: [String]
let desc: String
let homepage: String
let url: String
let version: String
let installed: String?
var outdated: Bool
enum CodingKeys: String, CodingKey {
case token, tap, name, desc, homepage, url, version, installed, outdated
case fullToken = "full_token"
}
enum CodingKeys: String, CodingKey {
case token, tap, name, desc, homepage, url, version, installed, outdated
case fullToken = "full_token"
}
}
struct Formulae: Codable {
struct Version: Codable {
let stable: String
let head: String?
let bottle: Bool
struct Version: Codable {
let stable: String
let head: String?
let bottle: Bool
enum CodingKeys: String, CodingKey {
case stable
case head, bottle
}
}
enum CodingKeys: String, CodingKey {
case stable
case head, bottle
}
}
let name: String
let fullName: String
let tap: String
let oldNames: [String]
let aliases: [String]
let versionedFormulae: [String]
let desc: String
let license: String?
let homepage: String
let versions: Version
let outdated: Bool
let name: String
let fullName: String
let tap: String
let oldNames: [String]
let aliases: [String]
let versionedFormulae: [String]
let desc: String
let license: String?
let homepage: String
let versions: Version
let outdated: Bool
enum CodingKeys: String, CodingKey {
case name
case tap
case aliases
case desc
case license
case homepage
case versions
case outdated
case fullName = "full_name"
case oldNames = "oldnames"
case versionedFormulae = "versioned_formulae"
}
enum CodingKeys: String, CodingKey {
case name
case tap
case aliases
case desc
case license
case homepage
case versions
case outdated
case fullName = "full_name"
case oldNames = "oldnames"
case versionedFormulae = "versioned_formulae"
}
}
struct InfoResponse: Codable {
let formulae: [Formulae]
let casks: [Cask]
let formulae: [Formulae]
let casks: [Cask]
enum CodingKeys: String, CodingKey {
case casks
case formulae
}
enum CodingKeys: String, CodingKey {
case casks
case formulae
}
}
@Observable
class Homebrew {
var data: InfoResponse?
var isLoading = false
var errorMessage: String?
var data: InfoResponse?
var isLoading = false
var errorMessage: String?
func getInfo(on query: String) {
self.isLoading = true
self.errorMessage = nil
self.data = nil
Task { [weak self] in
do {
let res = try shell("/opt/homebrew/bin/brew info --json=v2 \(query)")
if let data = res.data(using: .utf8) {
let output = try JSONDecoder().decode(InfoResponse.self, from: data)
self?.data = output
}
} catch {
self?.errorMessage = error.localizedDescription
}
self?.isLoading = false
}
}
func getInfo(on query: String) {
self.isLoading = true
self.errorMessage = nil
self.data = nil
Task { [weak self] in
do {
let res = try shell(
"/opt/homebrew/bin/brew info --json=v2 \(query)")
if let data = res.data(using: .utf8) {
let output = try JSONDecoder().decode(
InfoResponse.self, from: data)
self?.data = output
}
} catch {
self?.errorMessage = error.localizedDescription
}
self?.isLoading = false
}
}
func getInstalled() {
self.isLoading = true
self.data = nil
self.errorMessage = nil
Task { [weak self] in
do {
let res = try shell("/opt/homebrew/bin/brew info --json=v2 --installed")
if let data = res.data(using: .utf8) {
let output = try JSONDecoder().decode(InfoResponse.self, from: data)
self?.data = output
}
} catch {
self?.errorMessage = error.localizedDescription
}
self?.isLoading = false
}
func getInstalled() {
self.isLoading = true
self.data = nil
self.errorMessage = nil
Task { [weak self] in
do {
let res = try shell(
"/opt/homebrew/bin/brew info --json=v2 --installed")
if let data = res.data(using: .utf8) {
let output = try JSONDecoder().decode(
InfoResponse.self, from: data)
self?.data = output
}
} catch {
self?.errorMessage = error.localizedDescription
}
self?.isLoading = false
}
}
}
func isDownloaded(_ name: String) async -> Bool {
self.isLoading = true
self.errorMessage = nil
self.data = nil
let task = Task { [weak self] in
do {
let res = try shell("/opt/homebrew/bin/brew list -1 \(name) >/dev/null 2>&1; echo $?")
.trimmingCharacters(in: .whitespacesAndNewlines)
self?.isLoading = false
return res == "0"
} catch {
self?.errorMessage = error.localizedDescription
}
func isDownloaded(_ name: String) async -> Bool {
self.isLoading = true
self.errorMessage = nil
self.data = nil
let task = Task { [weak self] in
do {
let res = try shell(
"/opt/homebrew/bin/brew list -1 \(name) >/dev/null 2>&1; echo $?"
)
.trimmingCharacters(in: .whitespacesAndNewlines)
self?.isLoading = false
return res == "0"
} catch {
self?.errorMessage = error.localizedDescription
}
return false
}
return false
}
switch await task.result {
case .success(let success):
return success
case .failure(let fail):
return false
}
}
switch await task.result {
case .success(let success):
return success
case .failure(let fail):
return false
}
}
func install(_ fullToken: String, isCask: Bool = false) async -> Bool {
self.isLoading = true
self.data = nil
let task = Task { [weak self] in
do {
try shell("/opt/homebrew/bin/brew install \(isCask ? "--cask" : "") \(fullToken)")
} catch {
self?.errorMessage = error.localizedDescription
}
self?.isLoading = false
return await self?.isDownloaded(fullToken) ?? false
}
func install(_ fullToken: String, isCask: Bool = false) async -> Bool {
self.isLoading = true
self.data = nil
let task = Task { [weak self] in
do {
try shell(
"/opt/homebrew/bin/brew install \(isCask ? "--cask" : "") \(fullToken)"
)
} catch {
self?.errorMessage = error.localizedDescription
}
self?.isLoading = false
return await self?.isDownloaded(fullToken) ?? false
}
return switch await task.result {
case .success(let success):
success
case .failure(let fail):
false
}
}
return switch await task.result {
case .success(let success):
success
case .failure:
false
}
}
func uninstall(_ fullToken: String) async -> Bool {
self.isLoading = true
self.data = nil
let task = Task { [weak self] in
do {
let res =
try shell("/opt/homebrew/bin/brew uninstall \(fullToken); echo $?")
.trimmingCharacters(in: .whitespacesAndNewlines)
} catch {
self?.errorMessage = error.localizedDescription
}
self?.isLoading = false
return await !(self?.isDownloaded(fullToken) ?? true)
}
func uninstall(_ fullToken: String) async -> Bool {
self.isLoading = true
self.data = nil
let task = Task { [weak self] in
do {
try shell(
"/opt/homebrew/bin/brew uninstall \(fullToken)"
)
} catch {
self?.errorMessage = error.localizedDescription
}
self?.isLoading = false
return await !(self?.isDownloaded(fullToken) ?? true)
}
return switch await task.result {
case .success(let success):
success
case .failure(let failure):
false
}
return switch await task.result {
case .success(let success):
success
case .failure:
false
}
}
}
func update(_ name: String) async -> Bool {
self.isLoading = true
self.errorMessage = nil
self.data = nil
let task = Task { [weak self] in
do {
let res = try shell(
"/opt/homebrew/bin/brew upgrade \(name); echo $?"
)
.trimmingCharacters(in: .whitespacesAndNewlines)
self?.isLoading = false
return res == "0"
} catch {
self?.errorMessage = error.localizedDescription
}
self?.isLoading = false
return false
}
return switch await task.result {
case .success(let success):
success
case .failure:
false
}
}
}

View File

@@ -8,58 +8,59 @@
import SwiftUI
struct SearchView: View {
@State private var query = ""
@State private var brew = Homebrew()
var body: some View {
VStack {
TextField("Search", text: $query)
.padding()
.padding(.bottom, 0)
.onSubmit {
brew.getInfo(on: query)
}
Spacer()
if brew.isLoading {
ProgressView("Loading...")
} else if let data = brew.data {
List {
if !data.casks.isEmpty {
Section("Casks") {
ForEach(data.casks, id: \.fullToken) { cask in
HStack {
Text(cask.fullToken)
Spacer()
if cask.installed != nil {
Image(systemName: "checkmark.circle.fill")
.symbolRenderingMode(.palette)
.foregroundStyle(.white, .green)
} else {
DownloadButton(name: cask.fullToken, isCask: true)
}
}
}
}
}
if !data.formulae.isEmpty {
@State private var query = ""
@State private var brew = Homebrew()
var body: some View {
VStack {
TextField("Search", text: $query)
.onSubmit {
brew.getInfo(on: query)
}
Spacer()
if brew.isLoading {
ProgressView("Loading...")
} else if let data = brew.data {
List {
if !data.casks.isEmpty {
Section("Casks") {
ForEach(data.casks, id: \.fullToken) { cask in
HStack {
Text(cask.fullToken)
Spacer()
if cask.installed != nil {
Image(
systemName: "checkmark.circle.fill"
)
.symbolRenderingMode(.palette)
.foregroundStyle(.white, .green)
} else {
DownloadButton(
name: cask.fullToken, isCask: true)
}
}
}
}
}
if !data.formulae.isEmpty {
Section("Formulaes") {
ForEach(data.formulae, id: \.fullName) { formulae in
HStack {
Text(formulae.fullName)
}
}
}
}
}
} else if let errorMessage = brew.errorMessage {
Text(errorMessage)
.foregroundStyle(.red)
}
}
}
Section("Formulaes") {
ForEach(data.formulae, id: \.fullName) { formulae in
HStack {
Text(formulae.fullName)
}
}
}
}
}
} else if let errorMessage = brew.errorMessage {
Text(errorMessage)
.foregroundStyle(.red)
}
}
}
}
#Preview {
SearchView()
SearchView()
}

View File

@@ -6,31 +6,32 @@
//
import XCTest
@testable import Brewer
final class BrewerTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
// Any test you write for XCTest can be annotated as throws and async.
// Mark your test throws to produce an unexpected failure when your test encounters an uncaught error.
// Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
// Any test you write for XCTest can be annotated as throws and async.
// Mark your test throws to produce an unexpected failure when your test encounters an uncaught error.
// Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}

View File

@@ -9,33 +9,33 @@ import XCTest
final class BrewerUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests its important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
// In UI tests its important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTApplicationLaunchMetric()]) {
XCUIApplication().launch()
}
}
}
}

View File

@@ -9,24 +9,24 @@ import XCTest
final class BrewerUITestsLaunchTests: XCTestCase {
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override class var runsForEachTargetApplicationUIConfiguration: Bool {
true
}
override func setUpWithError() throws {
continueAfterFailure = false
}
override func setUpWithError() throws {
continueAfterFailure = false
}
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
func testLaunch() throws {
let app = XCUIApplication()
app.launch()
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
// Insert steps here to perform after app launch but before taking a screenshot,
// such as logging into a test account or navigating somewhere in the app
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
let attachment = XCTAttachment(screenshot: app.screenshot())
attachment.name = "Launch Screen"
attachment.lifetime = .keepAlways
add(attachment)
}
}