# Conditionally execute a command if a specific package is loaded

I am loading the gitver package based on the expl3 solution accepted for my question here.

However, I need to use some commands depending on whether the package has actually been loaded. For instance, using a combination of hyperxmp, hyperref and gitver, one can provide an option pdfversionid = \gitVer to the hypersetup command (see code below).

The question is, how do I conditionally detect the presence of a package loaded (gitver in my example) and set up this conditional compilation?

Minimal conceptual example:

\documentclass{article}
\usepackage{expl3}
\csname sys_if_shell_unrestricted:T\endcsname{\usepackage{gitver}}
\usepackage{hyperxmp}
\usepackage{hyperref}

% this commented paragraph is conceptual & needs fixing through a solution from this forum
% \hypersetup{%
% pdfversionid = {detect if gitver has been loaded & set to \gitVer if so; otherwise set to empty {}}
% }%

\begin{document}
Hello world!

% The following again describes my intended requirements in words
% detect if gitver has been loaded & print \versionBox{} if so; otherwise print "gitver not loaded"

\end{document}


Normally you would just use \@ifpackageloaded, but the command is limited to the preamble. To use it in the document body you need \ltx@ifpackageloaded from the ltxcmds package. Since the macro has an @ in the name, you need to wrap it in \makeatletter and \makeatother.

\documentclass{article}
\usepackage{expl3}
\usepackage{ltxcmds}
%\csname sys_if_shell_unrestricted:T\endcsname{\usepackage{gitver}}
\usepackage{hyperxmp}
\usepackage{hyperref}

\makeatletter
% this commented paragraph is conceptual & needs fixing through a solution from this forum
\hypersetup{pdfversionid = \gitVer}
}{
\hypersetup{pdfversionid = {}}
}
\makeatother

\begin{document}
Hello world!

\meaning\gitVer
% The following again describes my intended requirements in words
% detect if gitver has been loaded & print \versionBox{} if so; otherwise print "gitver not loaded"
\makeatletter
\makeatother

\end{document}


Assuming that \gitVer and \VersionBox are defined by gitver, just add

\providecommand{\gitVer}{}

This exploits the fact that \providecommand does nothing if the command is already defined.
• thank you. It worked for me. However, I think the ltxcmds package is a bit more flexible, and hence I'd like to accept that answer. However, yours is a valid solution and I am upvoting this. – Krishna Sep 19 '19 at 16:25