Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
200 changes: 200 additions & 0 deletions Sources/Skyflow/ProcessMarkdown.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import Foundation

func processMarkdownFiles(at directoryPath: String, fileNamesToDelete: [String]) {
let fileManager = FileManager.default
let directoryURL = URL(fileURLWithPath: directoryPath)

// Check if directory exists
if !fileManager.fileExists(atPath: directoryPath) {
print("Directory does not exist: \(directoryPath)")
return
}

do {
let fileURLs = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: nil)

for fileName in fileNamesToDelete {
let filesToDelete = fileURLs.filter { $0.pathExtension == "md" && $0.lastPathComponent == fileName }

for fileURL in filesToDelete {
try fileManager.removeItem(at: fileURL)
}
}

let filesToProcess = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: nil)

for fileURL in filesToProcess {
convertParamsToTable(at: fileURL)
}

} catch {
print("Error while processing files: \(error.localizedDescription)")
}
}

// Function to read markdown file, convert params to table, and update markdown
func convertParamsToTable(at fileURL: URL) {
guard var markdown = try? String(contentsOf: fileURL) else {
print("Failed to read markdown file: \(fileURL.path)")
return
}

markdown = extractHeadings(from: markdown)

// Array to store the updated lines of markdown
var updatedMarkdownLines: [String] = []

// Flag to indicate if a parameter list is being processed
var isProcessingParameters = false

// Array to store the lines of the current parameter list
var parameterList: [String] = []

var emptyLineCount = 0

updatedMarkdownLines.append("{% env enable=\"iosSdkRef\" %}")
updatedMarkdownLines.append("")

// Iterate over each line in the markdown
for line in markdown.components(separatedBy: .newlines) {
let startsWithParameters = line.range(
of: #"^#{2,4}\s*Parameters"#,
options: .regularExpression
) != nil
if startsWithParameters {
// Start of a new parameter list
isProcessingParameters = true
} else if isProcessingParameters && emptyLineCount == 2{
// End of the current parameter list

// Convert parameters list to a table
updatedMarkdownLines.append("")
let parameterTable = convertToTable(parameterList)
updatedMarkdownLines.append(contentsOf: parameterTable)
updatedMarkdownLines.append("")

// Reset the parameter list
parameterList = []
isProcessingParameters = false
emptyLineCount = 0
}

// Append the line to the updated markdown
if isProcessingParameters && !startsWithParameters{
if(line.isEmpty)
{
emptyLineCount = emptyLineCount + 1
}
parameterList.append(line)
} else {
if(line.starts(with: "``` swift"))
{
updatedMarkdownLines.append(line.replacingOccurrences(of: " ", with: ""))
}
else {
updatedMarkdownLines.append(line)
}
}
}

if isProcessingParameters && emptyLineCount == 2{
// For parameter list at the end of file

// Convert parameters list to a table
updatedMarkdownLines.append("")
let parameterTable = convertToTable(parameterList)

updatedMarkdownLines.append(contentsOf: parameterTable)
updatedMarkdownLines.append("")

// Reset the parameter list
parameterList = []
isProcessingParameters = false
emptyLineCount = 0
}

updatedMarkdownLines.append("{% /env %}")
updatedMarkdownLines.append("")
// Join the updated markdown lines
let updatedMarkdown = updatedMarkdownLines.joined(separator: "\n")

// print("Updated markdown: \(updatedMarkdown)")
// Write the updated markdown back to the file
do {
try updatedMarkdown.write(to: fileURL, atomically: true, encoding: .utf8)
print("Updated markdown written to: \(fileURL.path)")
} catch {
print("Error writing updated markdown: \(error)")
}
}

// Function to convert parameters to a table
func convertToTable(_ parameters: [String]) -> [String] {
var table: [String] = []
table.append("| Name | Description |")
table.append("| ---- | ----------- |")
for line in parameters {
if(!line.isEmpty)
{
let arr = line.split(separator: ":")
let name = arr[0].split(separator: "-")[1].trimmingCharacters(in: .whitespaces)
let description = arr[1].trimmingCharacters(in: .whitespaces)
table.append("| \(name) | \(description) |")
}
}
return table
}

func extractHeadings(from markdown: String) -> String {
var modifiedMarkdown = ""

let lines = markdown.components(separatedBy: .newlines)
var isInsideCodeBlock = false

for line in lines {
if line.starts(with: "```") {
isInsideCodeBlock.toggle()
}

if isInsideCodeBlock || !line.starts(with: "###") {
modifiedMarkdown += line + "\n"
} else if let methodName = extractMethodName(from: line) {
let hashes = line.components(separatedBy: " ")[0]
modifiedMarkdown += "\(hashes) \(methodName)\n"
}
}

return modifiedMarkdown
}

func extractMethodName(from line: String) -> String? {
let components = line.components(separatedBy: " ")
guard components.count > 1 else {
return nil
}

let methodName = components[1]
let sanitizedMethodName = sanitizeMethodName(methodName)
return sanitizedMethodName
}

func sanitizeMethodName(_ methodName: String) -> String {
let pattern = "\\([^()]*\\)"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: methodName.utf16.count)

var sanitizedMethodName = regex.stringByReplacingMatches(
in: methodName,
options: [],
range: range,
withTemplate: "()"
)
sanitizedMethodName = sanitizedMethodName.replacingOccurrences(of: "`", with: "")
// print("heading: \(sanitizedMethodName)")
return sanitizedMethodName
}
// Usage example
let path = "docs/markdown"
let filesToDelete = ["_Footer.md", "_Sidebar.md", "ContainerOptions.md", "Callback.md", "TokenProvider.md", "Label.md", "UILabel.md", "SkyflowLabelView.md", "Home.md", "RevealOptions.md", "FormatLabel.md"]

processMarkdownFiles(at: path, fileNamesToDelete: filesToDelete)
18 changes: 18 additions & 0 deletions Sources/Skyflow/collect/CollectContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,20 @@
import Foundation
import UIKit

/// Wraps all Collect Elements.
public class CollectContainer: ContainerProtocol {}

public extension Container {

/**
Creates a Collect Element.

- Parameters:
- input: Collect Element input.
- options: Collect Element options.

- Returns: Returns the Collect Element.
*/
func create(input: CollectElementInput, options: CollectElementOptions? = CollectElementOptions()) -> TextField where T: CollectContainer {
var tempContextOptions = self.skyflow.contextOptions
tempContextOptions.interface = .COLLECT_CONTAINER
Expand All @@ -22,6 +33,13 @@ public extension Container {
return skyflowElement
}

/**
Collects the data and sends it to the vault.

- Parameters:
- callback: Implementation of Skyflow.Callback.
- options: Collects the data and sends it to the vault.
*/
func collect(callback: Callback, options: CollectOptions? = CollectOptions()) where T: CollectContainer {
var tempContextOptions = self.skyflow.contextOptions
tempContextOptions.interface = .COLLECT_CONTAINER
Expand Down
10 changes: 10 additions & 0 deletions Sources/Skyflow/collect/CollectOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,20 @@

import Foundation

/// Options for a Collect Element.
public struct CollectOptions {
var tokens: Bool
var additionalFields: [String: Any]?
var upsert: [[String: Any]]?

/**
Initializes the Collect options.

- Parameters:
- tokens: If `true`, returns tokens for the collected data. Defaults to `true`.
- additionalFields: Additional, non-sensitive data to insert into the vault.
- upsert: Upsert configuration for the element.
*/
public init(tokens: Bool = true, additionalFields: [String: Any]? = nil, upsert: [[String: Any]]? = nil) {
self.tokens = tokens
self.additionalFields = additionalFields
Expand Down
9 changes: 9 additions & 0 deletions Sources/Skyflow/collect/InsertOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,18 @@

import Foundation

/// Contains additional parameters for the insert method.
public struct InsertOptions {
var tokens: Bool
var upsert: [[String: Any]]?

/**
Initializes the Insert options.

- Parameters:
- tokens: If `true`, returns tokens for the collected data. Defaults to `false`.
- upsert: If specified, upserts data. If not specified, inserts data.
*/
public init(tokens: Bool = true, upsert: [[String: Any]]? = nil) {
self.tokens = tokens
self.upsert = upsert
Expand Down
39 changes: 39 additions & 0 deletions Sources/Skyflow/core/Client.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,20 @@
import Foundation
import AEXML

/// This is the description for Client Class.
public class Client {
var vaultID: String
var apiClient: APIClient
var vaultURL: String
var contextOptions: ContextOptions
var elementLookup: [String: Any] = [:]

/**
Initializes the Skyflow client.

- Parameters:
- skyflowConfig: Configuration for the Skyflow client.
*/
public init(_ skyflowConfig: Configuration) {
self.vaultID = skyflowConfig.vaultID
self.vaultURL = skyflowConfig.vaultURL.hasSuffix("/") ? skyflowConfig.vaultURL + "v1/vaults/" : skyflowConfig.vaultURL + "/v1/vaults/"
Expand All @@ -22,6 +29,14 @@ public class Client {
Log.info(message: .CLIENT_INITIALIZED, contextOptions: self.contextOptions)
}

/**
Inserts data into the vault.

- Parameters:
- records: Records to insert.
- options: Options for the insertion.
- callback: Implementation of Skyflow.Callback.
*/
public func insert(records: [String: Any], options: InsertOptions = InsertOptions(), callback: Callback) {
var tempContextOptions = self.contextOptions
tempContextOptions.interface = .INSERT
Expand Down Expand Up @@ -95,6 +110,15 @@ public class Client {
}
}

/**
Creates a container.

- Parameters:
- type: Type of the container.
- options: Options for the container.

- Returns: Returns a container of the specified type.
*/
public func container<T>(type: T.Type, options: ContainerOptions? = ContainerOptions()) -> Container<T>? {
if options != nil {
// Set options
Expand All @@ -113,6 +137,14 @@ public class Client {
return nil
}

/**
Returns values that correspond to the specified tokens.

- Parameters:
- records: Records to fetch.
- options: Additional options for the reveal method.
- callback: Implementation of Skyflow.Callback.
*/
public func detokenize(records: [String: Any], options: RevealOptions? = RevealOptions(), callback: Callback) {
var tempContextOptions = self.contextOptions
tempContextOptions.interface = .DETOKENIZE
Expand Down Expand Up @@ -177,6 +209,13 @@ public class Client {
}
}

/**
Reveal records by Skyflow ID.

- Parameters:
- records: This is the description for records parameter.
- callback: Implementation of Skyflow.Callback.
*/
public func getById(records: [String: Any], callback: Callback) {
var tempContextOptions = self.contextOptions
tempContextOptions.interface = .GETBYID
Expand Down
10 changes: 10 additions & 0 deletions Sources/Skyflow/core/Configuration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,22 @@

import Foundation

/// Configuration for the Skyflow client.
public struct Configuration {
var vaultID: String
var vaultURL: String
var tokenProvider: TokenProvider
var options: Options?

/**
This is the description for init method.

- Parameters:
- vaultID: ID of the vault to connect to.
- vaultURL: URL of the vault to connect to.
- tokenProvider: An implementation of the token provider interface.
- options: Additional options for configuration.
*/
public init(vaultID: String = "", vaultURL: String = "", tokenProvider: TokenProvider, options: Options? = Options()) {
self.vaultID = vaultID
self.vaultURL = vaultURL
Expand Down
1 change: 1 addition & 0 deletions Sources/Skyflow/core/Env.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import Foundation

/// Supported environments.
public enum Env {
case DEV
case PROD
Expand Down
1 change: 1 addition & 0 deletions Sources/Skyflow/core/EventName.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import Foundation

/// Supported event names.
public enum EventName: String {
case CHANGE = "CHANGE"
case READY = "READY"
Expand Down
Loading