Excursion set theory, where density perturbations evolve stochastically with the smoothing scale, provides a method for computing the mass function of cosmological structures like dark matter haloes, sheets and filaments. The computation of these mass functions is mapped into the so-called first-passage time problem in the presence of a moving barrier. In this paper we use the path-integral formulation of the excursion set theory developed recently to analytically solve the first-passage time problem in the presence of a generic moving barrier, in particular the barrier corresponding to ellipsoidal collapse. We perform the computation for both Gaussian and non-Gaussian initial conditions and for a window function which is a top-hat in wavenumber space. The expression of the halo mass function for the ellipsoidal collapse barrier and with non-Gaussianity is therefore obtained in a fully consistent way and it does not require the introduction of any form factor artificially derived from the Press–Schechter formalism based on the spherical collapse and usually adopted in the literature.