Store file at filepath in the database and return the base index entry
        Needs the git_working_dir decorator active ! This must be assured in the calling code
510946
def _store_path(self, filepath, fprogress):
        """"""
        st = os.lstat(filepath)     # handles non-symlinks as well
        if S_ISLNK(st.st_mode):
            # in PY3, readlink is string, but we need bytes. In PY2, it's just OS encoded bytes, we assume UTF-8
            open_stream = lambda: BytesIO(force_bytes(os.readlink(filepath), encoding=defenc))
        else:
            open_stream = lambda: open(filepath, 'rb')
        with open_stream() as stream:
            fprogress(filepath, False, filepath)
            istream = self.repo.odb.store(IStream(Blob.type, st.st_size, stream))
            fprogress(filepath, True, filepath)
        return BaseIndexEntry((stat_mode_to_index_mode(st.st_mode),
                               istream.binsha, 0, to_native_path_linux(filepath)))
1020486
def _get_subdirectory(cls, location):
        """"""
        # find the repo root
        git_dir = cls.run_command(['rev-parse', '--git-dir'],
                                  show_stdout=False, cwd=location).strip()
        if not os.path.isabs(git_dir):
            git_dir = os.path.join(location, git_dir)
        root_dir = os.path.join(git_dir, '..')
        # find setup.py
        orig_location = location
        while not os.path.exists(os.path.join(location, 'setup.py')):
            last_location = location
            location = os.path.dirname(location)
            if location == last_location:
                # We've traversed up to the root of the filesystem without
                # finding setup.py
                logger.warning(
                    "Could not find setup.py for directory %s (tried all "
                    "parent directories)",
                    orig_location,
                )
                return None
        # relative path of setup.py to repo root
        if samefile(root_dir, location):
            return None
        return os.path.relpath(location, root_dir)
285379
def normalized_path(dir = Dir.pwd, options = {})
      rootdir = (FalkorLib::Git.init?(dir)) ? FalkorLib::Git.rootdir(dir) : dir
      path = dir
      path = Dir.pwd if dir == '.'
      path = File.join(Dir.pwd, dir) unless (dir =~ /^\// || (dir == '.'))
      if (options[:relative] || options[:relative_to])
        root = (options[:relative_to]) ? options[:relative_to] : rootdir
        relative_path_to_root = Pathname.new( File.realpath(path) ).relative_path_from Pathname.new(root)
        path = relative_path_to_root.to_s
      end
      path
    end
724172
def default_index(func):
    

    @wraps(func)
    def check_default_index(self, *args, **kwargs):
        if self._file_path != self._index_path():
            raise AssertionError(
                "Cannot call %r on indices that do not represent the default git index" % func.__name__)
        return func(self, *args, **kwargs)
    # END wrapper method

    return check_default_index
220118
def _get_save_path(self, bury=False):
        """"""
        filename = self.get_filename(self[self._KEYS.NAME])

        # Put objects that shouldn't belong in this catalog in the boneyard
        if bury:
            outdir = self.catalog.get_repo_boneyard()

        # Get normal repository save directory
        else:
            repo_folders = self.catalog.PATHS.get_repo_output_folders()
            # If no repo folders exist, raise an error -- cannot save
            if not len(repo_folders):
                err_str = (
                    "No output data repositories found. Cannot save.\n"
                    "Make sure that repo names are correctly configured "
                    "in the `input/repos.json` file, and either manually or "
                    "automatically (using `astrocats CATALOG git-clone`) "
                    "clone the appropriate data repositories.")
                self.catalog.log.error(err_str)
                raise RuntimeError(err_str)

            outdir = repo_folders[0]

        return outdir, filename
404839
def workdir=(dir)
      workdir = GitLib.find_workdir(dir)
      if workdir.nil?
        @workdir = dir
        logger.info { "Initializing new repository at #{dir}" }
        return command(:init)
      else
        @workdir = workdir
        logger.debug { "Opening existing repository at #{dir}" }
      end
    end
1224317
def get_src_path(self, obj, append_base=True):
        
        path = getsourcefile(obj)
        if self.src_root not in path:
            # this can happen with e.g.
            # inlinefunc-wrapped functions
            if hasattr(obj, "__module__"):
                path = "%s.%s" % (obj.__module__, obj.__name__)
            else:
                path = obj.__name__
            path = path.replace(".", "/")
        pre, post = path.rsplit(self.src_root + "/", 1)

        lineno = self.get_line_no(obj)
        lineno = "" if lineno is None else "#L{}".format(lineno)

        path = self.src_root + "/" + post + lineno
        if append_base:
            path = os.path.join(self.github_link, path)
        return path
1102764
def _locate_file(f, base_dir):
    
    if base_dir == None:
        return f
    file_name = os.path.join(base_dir, f)
    real = os.path.realpath(file_name)
    #print_v('- Located %s at %s'%(f,real))
    return real
168868
def gitdir(path = Dir.pwd)
      g = MiniGit.new
      g.find_git_dir(path)[0]
    end
643447
def toil_get_file(file_store, index, existing, file_store_id):
    """"""

    if not file_store_id.startswith("toilfs:"):
        return file_store.jobStore.getPublicUrl(file_store.jobStore.importFile(file_store_id))
    src_path = file_store.readGlobalFile(file_store_id[7:])
    index[src_path] = file_store_id
    existing[file_store_id] = src_path
    return schema_salad.ref_resolver.file_uri(src_path)
1372346
private void initClonedRepository() throws GitAPIException, IOException {
		if (!getUri().startsWith(FILE_URI_PREFIX)) {
			deleteBaseDirIfExists();
			Git git = cloneToBasedir();
			if (git != null) {
				git.close();
			}
			git = openGitRepository();
			if (git != null) {
				git.close();
			}
		}

	}
296340
def create_working_dir(config, prefix):
    '''
        
    '''
    # Fetch base directory from executor configuration
    basepath = config.get("Execution", "directory")

    if not prefix:
        prefix = 'opensubmit'

    finalpath = tempfile.mkdtemp(prefix=prefix + '_', dir=basepath)
    if not finalpath.endswith(os.sep):
        finalpath += os.sep
    logger.debug("Created fresh working directory at {0}.".format(finalpath))

    return finalpath
1158375
def in_git_clone():
    
    gitdir = '.git'
    return os.path.isdir(gitdir) and (
        os.path.isdir(os.path.join(gitdir, 'objects')) and
        os.path.isdir(os.path.join(gitdir, 'refs')) and
        os.path.exists(os.path.join(gitdir, 'HEAD'))
    )
406292
def get_directory_relative_to_git_root(directory: str):
    
    return os.path.relpath(os.path.realpath(directory), get_git_root_directory(directory))
677348
def checkout(self, reference: str):
        
        LOGGER.info('checking out: %s', reference)
        if not self.index_is_empty():
            LOGGER.error('index contains change; cannot checkout. Status:\n %s', self.status())
            sys.exit(-1)
        if self.is_dirty(untracked=True):
            LOGGER.error('repository is dirty; cannot checkout "%s"', reference)
            LOGGER.error('repository is dirty; cannot checkout. Status:\n %s', self.status())
            sys.exit(-1)

        LOGGER.debug('going through all present references')
        for head in self.repo.heads:
            if head.name == reference:
                LOGGER.debug('resetting repo index and working tree to: %s', reference)
                self.repo.head.reference = head
                self.repo.head.reset(index=True, working_tree=True)
                break
        else:
            LOGGER.error('reference not found: %s', reference)
            sys.exit(-1)
842568
def read_committed_file(gitref, filename):
    
    repo = Repo()
    commitobj = repo.commit(gitref)

    blob = commitobj.tree[_delta_dir() + filename]
    return blob.data_stream.read()
120620
def get_git_status(git_path='git'):
    
    status_output = subprocess.call((git_path, 'diff-files', '--quiet'))
    if status_output != 0:
        return 'UNCLEAN: Modified working tree'
    else:
        # check index for changes
        status_output = subprocess.call((git_path, 'diff-index', '--cached',
                                         '--quiet', 'HEAD'))
        if status_output != 0:
            return 'UNCLEAN: Modified index'
        else:
            return 'CLEAN: All modifications committed'