Saturday, July 23, 2016

osx how to drag and drop to a php command line script (or, any script) // hack hack hack

Sorry for the clumsy blog entry title, I'm trying to up the google juice.

Digging my way out of problems with iTunes, I would like to drag a music file from my old archive to a new location; but the gotcha is I want it to copy a subset of the the path (containing the artist and album info) from the source folder to the destination folder.

Most "drag and drop" / PHP googling shows how to make an upload web application. (And obviously, it's probably weird that I've started using PHP so much for this stuff - but since I grew up with Perl as both a command line scripting tool and a cgi resource, it makes a kind of sense.)  If memory serves, on Windows I used to be able to drop a file onto a script file in Explorer, and it would run the script with the file as an argument, but that trick doesn't seem to work on OSX. Or MacOS. Whatever. (Incidentally, for the PHP upload case, I've had great luck with dropzone.js)

So, to the Terminal! (Obviously one of the big appeals of MacOS for a certain flavor of geek was a proper shell terminal vs a DOS Window.) We're going to leverage how dragging a file onto a Terminal window puts in the file path - but it would be annoying to have to type "php myscript.php" before each drag operation, so I'm going to make a convenience script, called "c", just so the name is easy to type:

#!/bin/sh
php copyIncludeSubpath.php "$@"

And then, for EXTRA typing laziness, I'm going to add the current directory to the path (not a good practice in general, but ok for a temporary Terminal window, to save typing ./ all the time)


export PATH=$PATH:.

Anyway, here's the script:
<?php
$oldroot = "/Volumes/My Book/monk/data/music/";
$newroot = "/Users/kisrael/Dropbox/dev/2016/scripting/LibraryXMLCompare/musicToAdd/";
for($i = 1; $i < count($argv);$i++){ #go over everything passed in, skipping name of php script
    $path = $argv[$i];
    copyFileFromRootToRoot($path,$oldroot,$newroot);
}
function copyFileFromRootToRoot($path, $oldroot,$newroot){
    if(substr($path,0,strlen($oldroot)) != $oldroot) { #check for oldroot at start of path
        print "$path doesn't start with $oldroot!\n";
        return;
    }
    $mainpart = substr($path, strlen($oldroot)); #get relevant part of path
    $oldloc = $oldroot.$mainpart;
    $newloc = $newroot.$mainpart;
    $path = substr($newloc,0,strrpos($newloc,DIRECTORY_SEPARATOR)); #get path minus file name
    if(! is_dir($path)) @mkdir($path, 0777, true);  #make it, eating errors
    copy($oldloc, $newloc) || print "FAIL ON $newloc\n";
}
?>
It's a little clumsy, but does the job.

No comments:

Post a Comment