Scroll to navigation

arename(1) User Contributed Perl Documentation arename(1)

NAME

arename - automatically rename audio files by tagging information

SYNOPSIS

arename [OPTION(s)] FILE(s)...

OPTIONS AND ARGUMENTS

--ambiguous-use-first
Sets the ambiguoususefirst option. See below for details.
--compare-versions
Prints the version of the arename script and the version of the Perl module, that contains most of the code. These versions should be the same. If not, that would indicate a possibly broken installation.
--copy (short option: -c)
Copy files instead of renaming (moving). This can be useful to copy tracks from your audio archive to a portable device for example.
--debug
Enable debugging output. This actually sets `verbosity' to 10000. This output option will cause very noisy output. You probably want something less verbose, like `--verbosity 20'.
--disable-hooks (short option: -H)
Do not make use of hooks of any sort (neither global nor local ones).
--disable-profiles (short option: -N)
Do not use configuration profiles (see below). Overwrites the useprofiles setting.
--dryrun (short option: -d)
Go into dryrun mode. This means, that no action will be taken. arename will print what it would do, if called without -d.
--enable-hooks
Explicitly enable hooks.
--force (short option: -f)
Overwrite files if needed.
--help (short option: -h)
Display a short help text.
--list-cfg (short option: -L)
List the current configuration in the actual configuration format.
--list-file-types
Lists all file types currently supported by arename, one type per line.
--list-exts-for-type <type[,type[,...]]>
Lists all extensions recognised file name extsionsion for type <type>, one extension per line. If a list of types is given as a comma-separated list, extensions for all listed types are listed.
--list-profiles (short option: -S)
Print a list of profile names defined in the active configuration. (This is primarily used by the zsh completion for the --profile option.)
--read-local (short option: -l)
Read a local config file (./.arename.local). Overwrites the uselocalrc configuration setting.
--stdin (short option: -s)
Read filenames from stdin after processing files given on the command line. It reads one file name per line, which means that file names containing newlines are not supported.
--version (short option: -V)
Display version information.
--verbosity <integer-value>
Sets the `verbosity' setting to `integer-value'.
--suppress-skips (short option: -Q)
When a file is skipped, because its name would not change, this option will cause arename to suppress any output. This sets the `suppress_skips' option.

Note that if the `verbosity' setting is at a high enough level, you may still get messages about the file being processed in the first place.

--rc <file>
Read file instead of ~/.arenamerc.
--post-rc <file>
Read file after ~/.arenamerc and before ./.arename.local.
--prefix <prefix> (short option: -p)
Define a prefix for destination files.
--profile <profile(s),...> (short option: -P)
Define a list of one or more profiles to use forcibly, no matter if they would be activated normally or not.
--compilation-template <template> (short option: -T)
Define a template, that will be used for files that contain a compilation tag.
--template <template> (short option: -t)
Define a generic template (for all files that do not contain a compilation tag).
--userset <variable=value> (short option: -u)
Set a user defined variable to a given value (see "User defined variables" below).
FILE(s)...
Input files, that are subject for renaming.

A word about option name stability: With arename version 3.0 we are now using Getopt::Long for parsing command lines options. That change was made, because the meaningful single letter options where used up. Every option is available via a --long-option. That interface will remain stable. If changes to the --long-option interface are done, that will happen with an appropriate deprecation phase, so users can adjust. So, if you want to use arename in scripts, those are the options you should use. There are currently no plans of removing or changing any further short options, but there are no guarantees. If it is indeed better to change a short option, we will do so.

A list of options that changed from arename 3.x to 4.0 can be found in the project's CHANGES file and general advice about incompatible changes from major version to major version are documented in the UPGRADING file.

Deprecated Command Line Options

The following options are deprecated and will be removed in a later version of arename.
--quiet
This option is a short hand for "--verbosity 10".
--uber-quiet
This option is a short hand for "--verbosity 5".
--verbose
This is a short hand for "--verbosity 20".

DESCRIPTION

arename is a tool that is able to rename audio files by looking at a file's tagging information. It uses this information to assemble a consistent destination file name. The user can define the format of the destination filename by the use of template strings.

Templates can be defined in the "Configuration files", by the template and comp_template settings (See "SETTINGS" below).

By default, arename will refuse to overwrite destination files, if the file in question already exists. You can force overwriting by supplying the --force option.

In order to see what would happen instead of actually modifying files, you can use the --dryrun option. This way you can avoid problems, that would occur if the situation (e.g. the information in the files or your configuration) is not exactly as you expected it.

Supported file formats

Since version 4.0, arename supports a lot more file formats than it used to (version 3.0 only supported .mp3, .ogg and .flac files). Thanks to Audio::Scan, we now support a much wider range of file types, of which most may exist using different file name extensions (e.g. *.ogg and *.oga are both of the type ogg).

You may use the `--list-file-types' and `--list-ext-for-type' options to find out which file type is mapped to which file name extensions.

If you would like support for another file type in arename, you will have to persuade the Audio::Scan developers to extend their module with said feature. Adding support for it in arename after that should be trivial.

To give you an idea, arename (in connection with Audio::Scan 0.85) let's you rename mp3, mp4, aac, ogg, flac, asf, musepack, monkey audio, wav (this type also supports aiff) and wavpack files.

Inputting a *lot* of files

arename can be used to keep the file names of whole audio archives in sync. However, that means that you will have to tell the script the location of many files, thousands maybe.

In order to do that you will face the problem, that on most UNIX-like systems, the length of the argument list for external programs is limited (recent Linux versions, as an exception, do not have that limitation anymore).

So, even if your shell can do recursive globbing like ksh or zsh, this will most likely get you into trouble (for more than just a few files):

  % arename -d **/*.mp3

There are several ways to overcome that limitation, of course.

The first solution is to use find in connection with arename's -s option:

  % find . -name "*.mp3" -print | arename -d -s

This will break for file names that contain newlines, because --stdin will read one file name per line from the standard input stream.

Another way of using find to deal with this problem is to use find's -exec option:

  % find . -name "*.mp3" -exec arename -d '{}' '+'

This will work for every possible file name. No matter if it has spaces or newlines in it. The + at the end of the call causes find to call the external program (arename in this case) with as many arguments as possible, without exceeding the limit. This requires a POSIXly correct find. GNU find for instance, did not support the + way for a long time. If you are stuck with an old version, you can exchange the + with a ; (note, that a semicolon must be quoted in any case), or use the xargs tool instead.

A last solution for zsh users would be zargs (which requires 'autoload zargs' in your zsh configuration):

  % zargs -- **/*.mp3 -- arename -d

GENERAL USAGE

When you are first confronted with arename and you try to get started with the documentation you might argue, that a 1000+ lines manual, that is not filled with too many examples is hardly starter-friendly.

Therefore, this section was introduced to give you the bare minimum of information in order to use the program without going through too much fuzz.

If you are really afraid of documentation, you could of course just read the output of the --help option and see which options to provide in order to get what you want. Then again, you will soon be pissed by the weird default values arename uses.

You will probably want other templates. After all, the ability to have these expanded strings is one of the points to use arename in the first place. They are described in the TEMPLATE section; and reading that section is the minimum effort you will want to go through.

After that, you can open the file ~/.arenamerc in your favourite text editor and resemble the following text (and presumably change the few values in there to your liking):

  # now you certainly want your own templates, so define them here
  # one for your normal files
  template &artist - &album - &tracknumber. &tracktitle

  # and another one for files that orignate from compilations
  comp_template va - &album - &tracknumber. &artist - &tracktitle

If you want more automation or more customization, you will not get around reading the manual below. If you need to solve special problems, the "HOOKS" part even further below is for you.

ENVIRONMENT VARIABLES

ARENAME_LOAD_QUIET
When set to 1, arename will not output any startup messages; not while reading the configuration or hook files, nor will arename emit messages about whether it is in copy mode or on a dry-run or similar.

However, if warnings or errors are encoutered while loading the configuration, those messages are still emitted, of course.

Any other value but 1 - and that includes ARENAME_LOAD_QUIET being absent from the environment - will cause arename to start up in its normal manner.

ARENAME_SUPPRESS_COLOURS
When set to 1 (and only 1 - arename will ignore any other setting), arename will turn off its output colourations. As of version 4.0, arename uses Term::ANSIColor to produce output, that features terminal colours.

FILES

arename's behaviour can be altered by a number of files it reads when starting up.

Normal configuration tasks are done in (how convenient) "Configuration files", described below.

If you need more control, or want to solve special problems you are having, you can do so by supplying Perl code in "Hook definition files".

arename can be configured to read configuration files as well as hook definition files from the current working directory. This feature is disabled by default, because they can be a security issue on multiuser systems.

There are no such things as system wide configuration files in arename.

For all setup files arename tries to find (except for the local ones) four different locations are tried. If the $XDG_CONFIG_HOME/arename directory exists, all files are expected to be there. If that directory does not exist, ~/etc/arename/ and if that is not there ~/.arename are are tried instead. If those directories could not be found either, arename will try to find the file it is looking for directly in the user's home directory.

The default for $XDG_CONFIG_HOME is ~/.config.

The first setup directory we find always wins. arename does not consider more than one setup directory.

If, for example, ~/etc/arename/ exists and we are looking for the normal configuration file (see below), but ~/etc/arename/rc could not be found, we do not try to find it in ~/.arename/ or the user's home directory.

Configuration files

arename uses up to three configuration files. As for most programs, the script will try to read a configuration file, that is located in the user's home directory. In addition to that, it will try to load local configuration files, if it finds appropriately named files in the current directory (and the uselocalrc feature is enabled):
$XDG_CONFIG_HOME/arename/rc
~/etc/arename/rc
~/.arename/rc
~/.arenamerc
per-user normal configuration file.
./.arename.local
per-directory local configuration file (only read if uselocalrc is set or the --read-local option is given on the command line).

The per-user normal configuration file can be substituted by another file, if specified via the --rc option.

Last but not least, you can specify an intermediate configuration file, that is read in between the normal and the per-directory file, via the --post-rc option.

File format

The format of the aforementioned files is pretty simple. It is parsed line by line. Empty lines, lines only containing whitespace and lines, whose first non whitespace character is a hash character (#) are ignored.

There are two different types of settings: boolean and scalar settings.

Booleans can be set like this:

  <setting> [true|false]

If the value is omitted, true is assumed. true and false are recognized case insensitively, and a value of 1 is synonymous to true, as is 0 to false.

Scalar settings are done in a very similar way:

  <setting> <value>

If the value is omitted, string values will be set to an empty string and numeric values will be set to zero.

In both cases, setting and value are separated by one or more whitespace characters. The value will be the rest of the line (all of it, including trailing whitespace).

If the value part starts with a backslash, that backslash is left out of the value. That makes it possible to define templates with leading whitespace.

If a line contains only a string within square brackets, that string is the start of a section. Section names are matches for starts of file names. That means, the settings following such a section definition will only applied for input file names that start with the same string as the section name. Where file name means the string, handed over to arename. The string ~/ at the beginning of a section name is expanded to the user's home directory.

You may start as many sections as you would like.

A section named /foo/bar/ supersedes a section named /foo/ for a file named /foo/bar/baz.ogg. So, the longest match wins.

Another possible configuration file entry is a user variable, which is defined via the set command. These settings are very different from the normal settings. Therefore, they are defined in a different way. That way is described in the "User defined variables" subsection below.

Last but not least, you may define so called profiles, see below.

Configuration profiles

Profiles are a very flexible and context sensitive way of using multiple configuration files at once. With profiles, local configuration files (and local hook definition files) can be substituted in a secure way; even on multi-user systems.

Reading local files (configs and hook-files) is still supported for backwards compatibility (see uselocalrc and uselocalhooks options). However, you are strongly encouraged to use profiles whenever you can.

As normal configuration files and global hook-files, profile-related files are searched in one of the setup directories described above. They are using the following naming conventions:

$XDG_CONFIG_HOME/arename/profile.PROFILENAME
~/etc/arename/profile.PROFILENAME
~/.arename/profile.PROFILENAME
~/.arename.PROFILENAME
Profile related configuration files; read if PROFILENAME is active.

They are read after a intermediate config file defined by --post-rc and a local config file (if enabled).

$XDG_CONFIG_HOME/arename/profile.PROFILENAME.hooks
~/etc/arename/profile.PROFILENAME.hooks
~/.arename/profile.PROFILENAME.hooks
~/.arename.PROFILENAME.hooks
Profile related "Hook definition files" (see below for details); read if PROFILENAME is active.

These files are read, between global and local hook-definition files.

In order to define profiles, you need to use the profile keyword:

  profile <name> <pattern>

Where name is a string, that is used in the place of PROFILENAME in the file location lists above. This name may contain of the following character range: a-zA-Z0-9_-

pattern is part of a Perl regex pattern (see perlreref and perlretut manpages). The pattern will be anchored at the beginning and is open at the end, somewhat like this pseudocode:

  if ($working_directory =~ m/^PATTERN/) { use_this_profile(); }

Example:

  profile music /mnt/audio/music/

Will cause the profile music to be active when the working directory is /mnt/audio/music/ or below. So, do not be afraid. You can use profiles without understanding regular expressions.

Like many other values in arename's configuration, a leading backslash of a pattern will be ignored to allow patterns, that start in white spaces. Furthermore, if a pattern starts in ~/, that string is replaced by the user's home directory.

You may add as many patterns to a profile name, as you want:

  profile music /mnt/audio/music/
  profile music /mnt/extern/audio/music/

The above activates the music profile in /mnt/audio/music/ and /mnt/extern/audio/music/, for example.

More than one profile can be activated at the same time. If that is true, the according configuration files are read in lexical order.

Sections versus Profiles

Since arename provides two context sensitive configuration facilities, you might ask yourself when to use which, when you are confronted with both for the first time.

First of all, profiles are more powerful. They may even introduce new hooks for arename to use. But that is not the conceptual difference between the two.

sections are sets of configuration settings, that are considered for each and every input file and they are only enabled for input files, whose name matches the section name.

profiles on the other hand are sets of configuration and hook-definition files, whose inclusion in the current arename run is decided at the beginning of the program's execution (not for every input file) - namely, if the name of the current working directory matches one of the profile's patterns.

That means, that if you need to introduce slight configuration changes based on an input file's name you want to use a section.

If you need to make broader configuration changes, considering the name of the current working directory, profiles are the way to go.

Of course, profile configuration files may introduce new sections, too.

Configuration file example

  # switch on verbosity
  verbosity 20

  # canonicalize file names before working with them
  canonicalize

  # the author is crazy! use a sane template by default. :-)
  template &artist - &album (&year) - &tracknumber. &tracktitle

  # activate the 'music' profile below /mnt/audio/music/.
  profile music /mnt/audio/music/

  # force files from /foo/bar/ to stay below that directory
  [/foo/bar/]
  prefix /foo/bar

Hook definition files

$XDG_CONFIG_HOME/arename/hooks
~/etc/arename/hooks
~/.arename/hooks
~/.arename.hooks
Defines global hooks, that are in effect in every directory if the usehooks option is set to true.
./.arename.hooks.local
This allows you to define special hooks, that will only be applied for processes that run in the directory the local file is found (and if the uselocalhooks option is set to true).

For details about hooks in arename, see "HOOKS" below.

SETTINGS

The following settings are supported in all configuration files.

Not all of them are usable in sections. The ones you can use in sections are: All default_* options, force, prefix, sepreplace, tnpad, comp_template and template.

ambiguoususefirst
Some tag types support setting the sametag multiple times. The scanning backends before arename 4.0 did not support such tags. When this option is set to false (default), arename gives up when it encounters such tags.

When set to true, arename just uses the first value it encounters.

For maximum control over how tags with ambiguous values are handled, you may use the `ambiguoustag' hook. (default: false)

canonicalize
If set, a given file name will be transformed to its cleaned up absolute path. You may want to set this, if you are using sections in the configuration. If you do not use sections, all this will give you is a performance penalty. (default value: false)
checkprofilerc
If set, arename will check if there is a configuration file for a profile as soon as it reads a profile definition in the setup and only consider the profile if it found the according config file. Profiles without config file will cause a warning if this is set, which may cause the dryrun option to be set if the warningsautodryrun option is set.

If unset, profiles without config file will not cause warnings. You will see messages about missing configuration files, if a profile without config file is active. (default: true)

checktemplatesinitially
If set, arename will inspect all template and comp_template settings for possible problems. Unsetting this option probably only makes sense, if you are working with templates within hooks and know what you are doing. Normal users will most likely want to stick with the default. (default: on)
comp_template
Defines a template to use with files that provide a compilation tag (for 'various artist' CDs, for example). This setting can still be overwritten by the --compilation-template command line option. (default value: va/&album/&tracknumber - &artist - &tracktitle)
default_*
default_artist, default_album, default_compilation, default_genre, default_tracknumber, default_tracktitle, default_year

Defines a default value, for the given tag in files, that lack this information. (default value: undefined)

hookerrfatal
If this is set to false, arename will continue execution even if reading, parsing or compiling a hooks file failed. (default value: false)
prefix
Defines a prefix for destination files. Setting this to '/foo/bar' results in destination files named '/foo/bar/Expanded Template.ogg'

This setting can still be overwritten by the --profile command line option. (default value: .)

sepreplace
Tagging information strings may contain slashes, which is a pretty bad idea on most file systems. Therefore, you can define a string, that replaces slashes with the value of this setting. (default value: _)
suppress_skips
Like the `--suppress-skips' command line option, this disables messages for files that arename will skip because the file name would not change.
template
Defines a template to use with files that do not provide a compilation tag (or where the compilation tag and the artist tag are exactly the same). This setting can be overwritten by the --compilation-template command line option. (default value: &artist[1]/&artist/&album/&tracknumber - &tracktitle)
template_aliases
If this option is set, arename allows the use of abbreviated taq names in template and comp_template. See "Available expression identifiers" below for details. (default value: off)
tnpad
This defines the width, to which the track number field is padded with zeros on the left. Setting this to zero disables padding. (default value: 2)
usehooks
If set to true, use hooks defined in ~/.arename.hooks. (default value: true)
uselocalhooks
If set to true, use hooks defined in ./.arename.hooks.local. (default value: false)
uselocalrc
If set to true, read a local configuration file (./.arename.local), if it exists. (default value: false)
useprofiles
If set to true, configuration profiles will be used. If false, they are not. (default value: true)
usetypeasextension
One file type may be used for different file name extensions. For example, files matching *.ogg and *.oga will both be handled as type ogg in Audio::Scan (the information gathering backend, arename is using since version 4.0).

When this option is set to true, a file matching *.oga would be renamed using .ogg as the extension, since its type is ogg. Otherwise, the original extension is left untouched. (default: true)

verbosity
Integer option, that sets the verbosity of arename's output. The default value is `10'. The `--verbosity' option may be used to override this setting.
warningsautodryrun
Switches on the dryrun option (if not enabled already), as soon as the configuration file parser encounters non-fatal warnings. This option was introduced to avoid destructive behaviour due to incorrect lines in any of the configuration files. (default value: true)

Deprecated Settings

verbose
This setting has no effect and will be removed in a later version. Use an appropriate `verbosity' setting instead.
quiet
This setting has no effect and will be removed in a later version. Use an appropriate `verbosity' setting instead.
quiet_skip
This setting has no effect and will be removed in a later version. Use an appropriate `verbosity' setting instead.
debug
This setting has no effect and will be removed in a later version. Use an appropriate `verbosity' setting instead.

User defined variables

You can use the set command in arenamerc files. This way the user can define his own variables. The namespace is separate from arename's normal settings. (That means, you cannot, for example, overwrite the internal template variable with this command.)

The sytnax is quite simple (and different to normal settings on purpose!):

set varname = value

There may be an arbitrary amount of whitespace around the equal sign (including no whitespace at all). If you want to have a value that starts in a whitespace character, you may start the value with a backslash character (just like with the normal settings, a leading backslash is always ignored).

You may also set user defined variables on the command line by using the --userset option:

  % arename --userset variable0=value
  % arename -u variable0=value

User defined variables are useful to make hooks configurable (see "HOOKS" below). Starting with version 4 of arename, user defined variables may also be defined within sections, which (just like normal option) makes them applicable only if said section is used for a given file.

TEMPLATE FORMAT

arename's templates are fairly easy to understand, but powerful.

At simplest, a template is just a fixed character string. However, that would not be exactly useful, because then every file you would ever want to rename would be getting the exact same name. That is why arename is able to expand certain expressions with information gathered from the file's tagging information.

An expression basically looks like one of the following forms:

&identifier
This is the `trivial' expression. It will expand to the information stored within the corresponding tag. If the tag in question is not available, the expansion of the template string will fail.
&identifier[length]
The `sized' expression. The length modifier in square brackets defines the maximum length, to which the expression should be expanded.

That means, if the artist of a file reveals to be 'Frank Zappa', then using '&artist[1]' will expand to 'F'.

&{identifier:default-template}
This is the first complex expession, called `complex-default'. When the tag, which corresponds to `identifier' is available, this expression will expand exactly like the trivial expression would.

If it is not available though, the expansion doesn't fail, but instead the `default-template' string is expanded.

&{identifier?set-template!unset-template}
This expansion is called `complex-set-unset'. Again, what will be used during template expansion depends on whether the tag which corresponds to `identifier' is set or not.

If it is set, the string set-template is expanded; if it is unset, the unset-template string is used.

Both simple expansions may be used with braces, like the complex expansions are:

&{identifier}
This is equal to `&identifier'.
&{identifier[length]}
And this is equal to `&identifier[length]'.

Backslashes are special in template strings, because they are used to quote characters that bear special meaning (for example, to get a ampersand character, you need to use "\&"). To get an actual backslash in the resulting string, you need to use a backslash, quoted by a backslash. A backslash on non-special characters is silently dropped.

Nesting expressions

In complex expressions, the strings called `default-template', `set-template' and `unset-template' are subject to regular template expansion. Hence, expressions like the following are possible:

  "&{album?&album/!}"

If `album' were set, it would expand to its value followed by a slash; otherwise it would expand to nothing. Using this, it is fairly easy to deal with album-less tracks:

  "&artist/&{album?&album/&tracknumber. !-no-album-/}&tracktitle"

That will effectively use the following template if `album' is set:

  "&artist/&album/&tracknumber. &tracktitle"

But if it is not set, it will instead use this:

  "&artist/-no-album-/&tracktitle"

Caution has to be taken if certain characters are to be used within conditional template expressions. For example, to use a closing curly bracket in either of them, it needs to be quoted using a backslash character.

Similarly, if an exclamation mark is to be used in a `set-template', it needs to be quoted by a backslash to avoid the character being interpreted as the end of the `set-template' string.

Available expression identifiers

The data, that is expanded is derived from tagging information in the audio files. There are two kinds of information available. One is the purely informational tag (like a track's artist) and the other further describes the format of the audio file (like the file's bitrate).

If you are defining a lot of templates on the command line, you may find that these identifiers take quite a while to type. If the template_aliases option is set, you may use shorter alias names instead of the the real identifier. Available aliases are listed with their corresponding idetifier below.

This is a list of all all informational identifiers available for all file-types:

album
The album the currently processed track is part of. (alias: al)
artist
The artist for the current track. (alias: ar)
compilation
Compilation tags are not very stable across different file types. Usually, this is set to a string like "Various Artists" for tracks that are part of some sort of compilation album (like motion picture sound-tracks). (alias: cmp)
genre
The genre or content type of the audio file. (alias: gn)
tracknumber
The number of the position of the track on the disc. Obviously. However, this can be in the form of '12' or '12/23'. In the second form, only the part left of the slash is used. The tracknumber is a little special, as you can define to what width it should be padded with zeros on the left (see tnpad setting in "SETTINGS"). (alias: tn)
tracktitle
The title of the currently processed track. (alias: tt)
year
Chronological information about the track (usually the year a song was written or the year the album a track is part of was released). (alias: yr)

Here is a list of file-format information tag available for all file-types:

bitrate
The bitrate the file was recorded/encoded with. (alias: br)
channels
The number of channels available in the file (for example, this is `2' for stereo files). (alias: ch)
length_ms
The length of the track in milli-seconds. (alias: ln)
samplerate
The samplerate the file was recorded/encoded with. (alias: sr)

For all file-types, the following tags are generated from the ones listed above (for convenience):

kbitrate
Kilobits per second (bitrate / 1000). (alias: kbr)
ksamplerate
Kilosamples per second (samplerate / 1000). (alias: ksr)
length_sec
The length of the track in seconds. (alias: ls)

Some tags are only available for certain file-types. They are always called `type_*'. File-type specific identifiers do not have alias names. Here is a list of those tags:

flac_wordsize
The word-size used in a flac file. `24' if samples are 24 bits wide.
mp3_id3_version
The version of the id3 tag used in mp3 files (e.g. "ID3v2.3.0").
wav_id3_version
The same as `mp3_id3_version', but for wave files.

EXIT STATUS

arename returns zero if everything went fine; non-zero on fatal problems. This may change in future versions.

HOOKS

Before we start, a word of warning: Hooks can solve a lot of problems. That amount of flexibility comes at its price. All data passed to hook functions are references to the actual data in the script (except for the namespace argument, which is a copy). If you write hooks carelessly, arename will get back at you! HOOKS ARE A BIG HAMMER, THAT CAN CRUSH PROBLEMS AS WELL AS LIMBS!

You have been warned!

Discussion

The reason for implementing hooks was to have a simple way of post processing tags, filenames etc. without having to invent own magic in the configuration files, when Perl has regular expressions on steriods anyway. Hooks can do more then pure pre and post processing, because they are called in numerous places and give broad access to the script's data structures. Still, post processing is probably the most useful feature they implement.

Hooks are just Perl subroutines, which are defined in one of two files (see "FILES"). They are run at certain events during the execution of arename. The contents of the argument list for each hook depends on what hook is called (see the "List of hook events" below). However, the first argument (argument zero aka. $_[0]) to all hooks is the hook namespace, the subroutine is called in.

The global hooks file is read before the local one, which means, that this local file may overwrite and extend the definitions from the global file, as much as Perl permits. This also means, that hooks from the local file are run after the ones from the global file (unless you are using your own method of registering hooks; but if you do so, you know what you are doing anyway).

Subroutines must be registered to arename, to be known as hooks. Once registered, a subroutine can be removed from the known hooks, if requested (see "Utility subroutines" below).

The keys in various data hashes passed to the hooks can be one of the following: album, artist, compilation, genre, tracknumber, tracktitle, year.

Utility subroutines

Registration subroutines

There are two subroutines, that are used to tell arename about subroutines, you defined that shall become hooks.

register_hook(event, coderef)
Registers a code reference (read: your subroutine) for the given event. Example: register_hook('startup', \&custom_banner);
remove_hook(event, coderef)
Removes all entries of the code reference for the given event. Example: remove_hook('startup', \&custom_banner);

If the coderef was added more than once, all entries are removed.

File access and manipulation

The currently processed file name can be accessed via two subroutines:

get_file()
Returns the current file name as a string. This way, you can get the name of the currently processed file in every hook.
set_file(file name string)
This gives you the opportunity of manipulating the current file name. Be careful using this, because if you break the file name, arename cannot work properly.

With these, you could even change the file name of the processed file, while arename works on it (which you really should only do, if you know what you are doing).

User-defined-variable subroutines

Hooks can also use the data from user defined variables, via their Perl interface:

user_get(setting)
Returns the current value of setting. This is always a scalar value.
user_set(setting, value)
Change the value of setting to value.

Here is an example for user defined settings:

  # Assume, the user set the myvar-variable to "bar" in his
  # configuration file
  my $foo = user_get('myvar');    # $foo is now "bar"
  user_set('foo', "bar, baz");
  my $foo = user_get('myvar');    # $foo is now "bar, baz"

API for accessing to arename's internal configuration

You can also access the configuration data of arename itself:

get_opt(setting)
Returns the current value of setting. This is always a scalar value.
set_opt(setting, value)
Change the value of setting to value.

A list of settings arename will use: canonicalize, dryrun, force, hookerrfatal, prefix, quiet, quiet_skip, readstdin, sepreplace, tnpad, usehooks, uselocalhooks, uselocalrc, verbose, verbosity, comp_template and template.

If you want to actually change these settings, you should have a profound knowledge of arename's internals. Be careful.

API for default_* settings

If you need to access the current values of the default_* settings:

get_defaults(tagname)
Returns the value of default_tagname.
get_default_keys()
Returns a lexically sorted array of tag names of currently set default_* values.
set_default(tagname, value)
Sets the value of default_tagname to value.

Miscellaneous subroutines

And finally, a few miscellaneous functions ARename.pm provides, that might be of interest.

choose_template(data hash reference)
Return the appropriate template (normal versus compiliation template) by the data in the referenced data hash.
expand_template(template string, data hash reference)
Return the expanded version of template string. The information, that is used to do the expansion is taken from the referenced data hash.

Keep in mind that this function calls hooks itself. Avoid endless loops! See "Hooks when expanding the template" for details.

ensure_dir(directory)
Makes sure directory exists. Think: mkdir -p directory
file_eq(file0, file1)
Checks if the name file0 and the name file1 point to the same file. Returns 0, if one of the file names does not exist or if the files do not point to the same file, 1 otherwise.

Dies if it cannot stat one of the given files.

tag_supported(tagname)
Returns 1 if the tag tagname is supported by arename, 0 otherwise.
template_deep_inspect(template_string)
This tokenises a template string and then looks at the whole token tree, and tries to figure out any potential problems in it.

If tokenisation already failed, a negative value is returned. In case of any warnings with the token tree, zero is returned. If nothing came up, a positive value is returned.

This subroutine is called for the `template' and `comp_template' strings in all sections when arename starts. If the user chooses to change a template string in a hook it is recommended to use this function to avoid any errors due to broken templates.

xrename(src, dest)
Renames src to dest. Works across file systems, too. Dies if something fails.

List of hook events

This is a complete list of hooks events with descriptions.

The first argument (argument number "zero") for every hook is the name space they are called in. To find out the name of the currently processed file, use the get_file() subroutine described above.

Hooks in the main loop

These hooks are called at the highest level of the script.

canonicalize
This is called in the middle of the file name canonicalization process (but only if the canonicalize setting is set).

You can get the current file name via get_file(). The canonicalized file name is handed to you via the hook's arguments. The value from this argument will be assigned to the processed filename after the execution of this hook.

Arguments: 1: canonicalized file name

next_file_early
Called at the start of the main loop before any file checks and canonicalizations (if enabled) are done.

Arguments:

next_file_late
Called in the main loop after the file checks and canonicalizations are done.

In this context, file checks means tests for read-access and for whether the processed file is a symlink. arename will refuse to process symlinks and files it cannot read.

Arguments:

file_done
Called in the main loop after the file has been processed (unless filetype_unknown was triggered, see below).

Arguments:

filetype_unknown
Called in the main loop after the file was tried to be processed but the file type (the extension, specifically) was unknown.

Arguments:

filetype_known
Called when it has been established, that the file in question should theoretically be supported by arename.

Arguments: 1: the current file name extension 2: the file type that has been detected

pre_rename
This is triggered directly before the actual file renaming process starts. All information about the file has been gathered at this point.

Arguments: 1: the file type, 2: the extension that will be used to assemble the target filename, 3: the data hash

Hooks in the renaming procedure

When all data has been gathered, arename will go on to actually rename the files to their new destination name (which will be generated in the process, see "Hooks when expanding the template" below).

pre_apply_defaults
This is the first action to be taken in the renaming process. It is called even before the default values are applied.

Arguments: 1: data hash, 2: file extension

pre_template
Called before template expansions have been done.

Arguments: 1: data hash, 2: file extension

post_template
Called after the template has been expanded and the new file name has been completely generated (including the destination directory prefix).

Arguments: 1: data hash, 2: file extension 3: the generated new filename (including directory prefix and file extension)

post_ensure_dir
The destnation directory for the new file name may contain sub directories, which currently do not exist. This hook is called after it is ensured, every directory portion exists.

Arguments: 1: data hash, 2: file extension 3: the generated new filename (including directory prefix and file extension)

post_rename
This is the final hook in the actual renaming process. The file has been renamed at this point.

Arguments: 1: data hash, 2: file extension 3: the generated new filename (including directory prefix and file extension)

Hooks when expanding the template

These hooks are called when the template string is filled with the data from tags in the audio files. To do this, arename first tokenises the template string into a data structure, which is later used to assemble the target file name.

pre_expand_template
Called before any expansions are done.

Arguments: 1: the template string, 2: the data hash

post_expand_template
Called after all expansions have been done, right before the the resulting string is returned.

Arguments: 1: the template string (fully expanded), 2: the data hash

expand_template_pre_expand_tag
Called each time the value of an existing tag is expanded. This may be more than once, as tags may be used as often in a template as the user requires. At each point, this hook will be called right before the data was retrieved and post-processed (like zero-padding the `tracknumber' tag).

Arguments: 1: the tag's name, 2: the data hash

expand_template_post_expand_tag
Called each time the value of an existing tag is expanded. Like with the `expand_template_pre_expand_tag' hook, this may be more than once.

At each point, this hook will be called right after the data was retrieved and post-processed.

Arguments: 1: the value, which will be used for expansion, 2: the tag's name, 2: the data hash

Hooks while gathering information

These hooks are triggered while the tag information is extracted from the audio files arename is processing. This is done in two steps. First the Audio::Scan module is used to scan for the raw meta data information from the current file. Then arename's data hash is being filled with that data.

pre_scan
This hook is called right before any scanning has been done.

Arguments: 1: the type of the file being processed (`ogg' for ogg vorbis files)

post_scan
This is triggered as soon as Audio::Scan is done processing the current file, but before arename's data hash has been filled.

Arguments: 1: the type of the file being processed (`ogg' for ogg vorbis files), 2: the data structure returned by `Audio::Scan'

ambiguoustag
When the data hash is being filled it is possible, that for one arename tag (like `artist') multiple values where returned by Audio::Scan. This hook is triggered as soon as such a tag with ambiguous values is processed.

The hook may be used for maximum control over how ambiguous values are handled. To do this, the ambiguous value (passed as an array reference in the second argument) should be turned into the desired scalar value.

If the array reference is left as it is, the usual `ambiguoususefirst' behaviour is followed. The the option's description for details.

Arguments: 1: the name of the tag with the ambiguous value, 2: its current (ambiguous) value, 3: the data hash in its current form (obviously not all values will have been filled in at this point), 4: the data structure returned by Audio::Scan (see its documentation for details)

post_fill
Finally, the `post_fill' hook is called after the data hash has been filled. This is a good spot, if post-processing the values of individual tag is desired.

Arguments: 1: return code of the filling process (`0' in case of an error, `1' otherwise), 2: the type of the file being processed (`ogg' for ogg vorbis files), 3: the data structure returned by `Audio::Scan', 4: the data hash.

Miscellaneous hooks

apply_defaults
This is triggered before values from the default_* settings are applied to missing values in the audio file. This hook is only run if a default value for a tag will be used!

Arguments: 1: data hash, 2: current key

startup
Called directly after all the module initialisation is done, at the very start of the script. Configuration files will have been read, as well as hook files (obviously) and command line options will have been handled at this point already.

This hook may be useful for postprocessing the configuration as well as for debugging.

Arguments: 1: program name, 2: its version, 3: configuration hash, 4: array of supported tags, 5: the program's argument list

normal_quit
Called at the end of the script. This is reached if nothing fatal happened.

Arguments: 1: the program's argument list

Example

This is a very simple example for a hook file, that prints a custom banner and replaces all whitespace in the expanded template with underscores:

  sub my_banner {
      print "Hello World.\n";
  }
  register_hook('startup', \&my_banner);

  sub replace_spaces_by_underscore {
      my ($templateref, $datref) = @_;
      $$templateref =~ s/\s+/_/g;
  }
  register_hook('post_expand_template',
      \&replace_spaces_by_underscore);

Further examples can be found in the arename.hooks file of the distribution.

SEE ALSO

find(1), xargs(1), Audio::Scan.

VERSION

This manual describes arename version 4.0.

AUTHOR

Frank Terbeck <ft@bewatermyfriend.org>,

Please report bugs.

LICENCE

 Copyright 2007-2011
 Frank Terbeck <ft@bewatermyfriend.org>, All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

   1. Redistributions of source code must retain the above
      copyright notice, this list of conditions and the following
      disclaimer.
   2. Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials
      provided with the distribution.

  THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS OF THE
  PROJECT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2017-07-31 perl v5.26.0