Это несоответствие типов - PullRequest
       4

Это несоответствие типов

0 голосов
/ 13 февраля 2020

Я новичок в AppleScript и не могу понять что-то. Почему функция valid_hex не возвращает true для этих элементов? Очевидно, что элементы данных правильно получают из tsv, читая абзацы и текстовые элементы 1 и 2, потому что выходная строка выглядит нормально.

Есть ли несоответствие типов, которое не позволяет valid_hex () выполнять свою работу?

set inputStr to "8-1 Black\t232323\r\n8-2 Brown\tB5674D\r\n8-3 Orange\tFF7538\r\n8-4 Yellow\tFCE883\r\n8-5 Green\t1CAC78\r\n8-6 Blue\t1F75FE\r\n8-7 Violet (Purple)\t926EAE\r\n8-8 Red\tEE204D"

set accepted to {}
set rejected to {}
set acceptedCount to 0
set rejectedCount to 0

set atids to AppleScript's text item delimiters
set AppleScript's text item delimiters to tab

repeat with p in (paragraphs of inputStr)
    set aLine to text of (p as string)

    repeat 1 times
        set colorName to text item 1 of aLine
        set hexColor to text item 2 of aLine

        log hexColor & " named " & colorName & " is valid: " & valid_hex(hexColor)

    end repeat

end repeat

on valid_hex(s)
    set validhex to {"#", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "a", "b", "c", "d", "e", "f"}
    if not (length of s = 6 or (length of s = 7 and s begins with "#")) then return false

    repeat with c in (text items of s)
        if validhex contains c then
            set status to true
        else
            set status to false
            exit repeat
        end if
    end repeat
    return status
end valid_hex

ОБНОВЛЕНИЕ: Исходя из принятого ответа, исходная проблема была решена. Это полный сценарий. Он берет разделенный список шестнадцатеричных цветов с именами и создает папку XCode.colorset для каждого из них, который можно перетаскивать непосредственно в каталог активов XCode для использования в качестве именованного цвета.

Он работает довольно хорошо, но если создается файл ошибки, он не go в тот же working_folder.

use AppleScript version "2.5"
use framework "Foundation"
use scripting additions

try
    set src to (choose file with prompt "choose input file")
    set o to (open for access src)
    set inputStr to (read o)
    close access o
end try

tell application "Finder"
    set working_path to container of (src) as string
end tell

set accepted to {}
set rejected to {}
set acceptedCount to 0
set rejectedCount to 0

repeat with aLine in (get paragraphs of inputStr)
    set old_delimits to AppleScript's text item delimiters -- Save the original delimiters
    set AppleScript's text item delimiters to tab
    set {colorName, hexColor} to text items of aLine
    set AppleScript's text item delimiters to old_delimits -- Restore the original delimiters

    repeat 1 times
        if not valid_hex_color(hexColor) then
            set rejectedCount to rejectedCount + 1
            copy "Rejected " & "\"" & colorName & "\"" & " with hex value: " & hexColor & "\n" to the end of rejected
            exit repeat
        else
            set acceptedCount to acceptedCount + 1
            set redComponent to text 1 thru 2 of hexColor
            set greenComponent to text 3 thru 4 of hexColor
            set blueComponent to text 5 thru 6 of hexColor
            set jsonString to "{\n\t\"info\": {\n\t\t\"version\": 1,\n\t\t\"author\": \"xcode\"\n\t},\n\t\"colors\": [\n\t\t{\n\t\t\t\"idiom\": \"universal\",\n\t\t\t\"color\": {\n\t\t\t\t\"color-space\": \"srgb\",\n\t\t\t\t\"components\": {\n\t\t\t\t\t\"red\": \"0x" & redComponent & "\",\n\t\t\t\t\t\"green\": \"0x" & greenComponent & "\",\n\t\t\t\t\t\"blue\": \"0x" & blueComponent & "\",\n\t\t\t\t\t\"alpha\": \"1.000\"\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t]\n}"


            tell application "Finder"

                set folderName to colorName & ".colorset"
                set fldr to (make new folder at working_path with properties {name:folderName})

            end tell

            set resultFilePath to (working_path as string) & folderName & ":Contents.json"
            set outFile to (open for access resultFilePath with write permission)
            write jsonString to outFile starting at 0
            close access outFile


            copy colorName & "\n" to the end of accepted

        end if
    end repeat
end repeat

if rejectedCount > 0 then
    set summary to "\nrejected " & rejectedCount & ":\n--------------------\n" & rejected & "\naccepted " & acceptedCount & ":\n--------------------\n" & accepted

    set errorFilePath to (working_path as string) & ":RejectedItems.txt"

    log working_path & errorFilePath

    set errorFile to (open for access errorFilePath with write permission)
    write summary to errorFile starting at 0
    close access errorFile

    display dialog ("Rejected " & rejectedCount & " items, see " & errorFilePath & ".")
end if

on valid_hex_color(s)
    set validhex to "0123456789ABCDEF"
    if s begins with "#" then set s to text 2 thru -1 of s
    if the length of s ≠ 6 then return false

    repeat with c in characters of s
        if validhex does not contain c then return false
    end repeat

    true
end valid_hex_color

1 Ответ

1 голос
/ 13 февраля 2020

Проблема в строке

repeat with c in (text items of s)

На данный момент text item delimiters установлен на tab, поэтому существует только один текстовый элемент, который всегда является всей строкой.

Чтобы получить каждый символ, замените его на

repeat with c in (get characters of s)

Ключевое слово get важно, чтобы получить список только один раз.

Первый повтор l oop немного громоздок, это достаточно

repeat with aLine in (get paragraphs of inputStr)
    set {colorName, hexColor} to text items of aLine
    log hexColor & " named " & colorName & " is valid: " & valid_hex(hexColor)
end repeat

И не забудьте сбросить text item delimiters

set AppleScript's text item delimiters to atids

Более сложный способ проверки строки - с помощью AppleScriptObj C и Регулярного выражения ( поместите строки use в начало скрипта)

use AppleScript version "2.5"
use framework "Foundation"

on valid_hex(s)
    set regex to current application's NSRegularExpression's regularExpressionWithPattern:"^#?[0-9A-Fa-f]{6}$" options:0 |error|:(missing value)
    return (regex's numberOfMatchesInString:s options:0 range:{location:0, |length|:(count s)}) as integer is 1
end valid_hex
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...