4 votos

archivo gzip en el buscador

¿Es posible añadir gzip (o cualquier otro comando de línea de comandos) como opción cuando se hace clic con el botón derecho en los archivos en el Finder? Hay una opción "Comprimir", pero hace un zip.

3voto

David Anderson Puntos 2189

Puede utilizar la aplicación Automator para crear una acción rápida, que puede ejecutar gzip (o cualquier otro comando de la línea de comandos) como opción al hacer clic con el botón derecho del ratón sobre archivos o carpetas en la aplicación Finder. La acción rápida debe ser almacenada como un .workflow en su archivo ~/Library/Services carpeta. A continuación se muestra un ejemplo, donde el gzip -r puede ejecutarse en los archivos seleccionados. El AppleScript puede ser modificado para ejecutar otros comandos.

Nota: Este ejemplo se realizó con MacOS Monterey versión 12.5. También probé usando MacOS High Sierra versión 10.13.6. Antes de la versión 10.14 de macOS Mojave, las acciones rápidas se refieren a un servicio.

El AppleScript puede parecer largo, pero tiene las siguientes características:

  • Hay un diálogo emergente que pide al usuario que confirme antes de ejecutar el comando.
  • Hay un mensaje emergente cuando se produce un error. Este mensaje está actualmente truncado a 2000 caracteres.
  • Los mensajes de error completos se pueden ver con la aplicación de la consola.
  • La aplicación Finder actualiza la ventana que contiene los archivos seleccionados después de ejecutar el comando.

La imagen siguiente muestra cómo se configura la acción rápida en la aplicación Automator.

Monterey automator

A continuación, el AppleScript que se muestra parcialmente en la imagen anterior.

to truncateReturns from userstring
    repeat while (userstring ends with return)
        if userstring = return then return ""
        set userstring to text from beginning to item -2 of userstring
    end repeat
    return userstring
end truncateReturns

to replaceCharacters of userstring over maxlength by endstring
    if userstring ends with return then
        set userstring to truncateReturns from userstring
    end if
    if length of userstring > maxlength then
        set userstring to (text from beginning to item maxlength of userstring)
        set userstring to (truncateReturns from userstring) & endstring
    end if
    return userstring
end replaceCharacters

on finderLogger(input)
    set logger to "printf"
    repeat with listitem in input
        set liststr to listitem as string
        if liststr = "<date>" then
            set liststr to (do shell script "date  +'%Y-%m-%d %H:%M:%S'" as string)
        end if
        set logger to logger & " " & quoted form of liststr
    end repeat
    set logger to logger & " >> ~/Library/Logs/Finder.log"
    set stdout to do shell script logger
    return stdout
end finderLogger

to fileInfo for thelink given following:followingBoolean
    set thequoted to quoted form of thelink
    if followingBoolean is false then
        set cmd to "if [ -L " & thequoted & " ];then echo LNK;fi"
        set followingBoolean to (do shell script cmd) is not "LNK"
    end if

    if followingBoolean is false then
        set linkFolderHFS to (do shell script "dirname " & thequoted) as POSIX file as text
        set linkFileHFS to (do shell script "basename " & thequoted) as POSIX file as text
        tell application "Finder" to set thefile to file linkFileHFS of folder linkFolderHFS
    else
        set linkFullHFS to thelink as POSIX file as text
        tell application "Finder" to set thefile to alias linkFullHFS
    end if
    return thefile
end fileInfo

on run {input, parameters}
    set cmd to "gzip -r"
    set messagetext to "Do you want run gzip on"
    set wait to 3600
    set maxlength to 2000
    considering numeric strings
        if system version of (system info) < "10.14" then
            set workflowname to "service gzip"
        else
            set workflowname to "quick action gzip"
        end if
    end considering

    try
        set filecount to count of input
        if filecount = 0 then error "The list of items was empty."

        set filelist to ""
        set fullpath to ""
        repeat with currentfile in input
            set fullpath to POSIX path of currentfile
            if length of fullpath > 1 and text -1 of fullpath = "/" then
                set fullpath to text 1 thru -2 of fullpath
            end if
            set filelist to filelist & " " & quoted form of fullpath
        end repeat

        if filecount is not equal to 1 then
            set messagetext to messagetext & " " & filecount & " items?"
        else
            set fullinfo to fileInfo for fullpath without following
            set displayname to displayed name of fullinfo
            set filekind to kind of fullinfo
            set messagetext to messagetext & return & "“" & displayname & "” " & filekind & "?"
        end if
        tell application "Finder"
            activate
            with timeout of wait + 100 seconds
                set status to display dialog messagetext buttons {"Stop", "Continue"} with icon caution giving up after wait
            end timeout
        end tell
        if gave up of status then error "Time out occurred after wait for Continue button to selected."
        if button returned of status is not equal to "Continue" then return input
        set fullcommand to cmd & filelist & " 2>&1"
        set stdout to do shell script fullcommand
    on error errmsg number errnum
        try
            finderLogger({"%s %s: %s\\n", "<date>", workflowname, errmsg})
            error (replaceCharacters of errmsg over maxlength by "…")
        on error errmsg number errnum
            tell application "Finder"
                activate
                with timeout of wait + 100 seconds
                    display alert errmsg as critical giving up after wait
                end timeout
            end tell
        end try
    end try
    try
        tell application "Finder"
            activate
            tell front window
                update every item with necessity
            end tell
        end tell
    end try
    return input
end run

La imagen siguiente muestra un mensaje de error que aparece en el registro del Finder.

Monterey console


A continuación se muestran las imágenes correspondientes tomadas de la versión 10.13.6 de macOS High Sierra.

High Sierra automator

High Sierra console


También debo señalar que si usted no está interesado en tener una ventana emergente para confirmar y ser notificado cuando se produce un error, entonces usted podría simplemente modificar esta respuesta para utilizar el comando gzip -r .

AppleAyuda.com

AppleAyuda es una comunidad de usuarios de los productos de Apple en la que puedes resolver tus problemas y dudas.
Puedes consultar las preguntas de otros usuarios, hacer tus propias preguntas o resolver las de los demás.

Powered by:

X