有没有办法将 .gitignore 文件中的指定文件推送到源?

Is there a way to push specified files in the .gitignore file to origin?

我不希望某些文件被 git 跟踪,我用 .gitignore 文件将它们排除在外。但我想将它们推送到 origin 分支,因为当有人克隆项目时它们是必需的。
现在的问题是我可以在不添加和提交排除的文件的情况下执行此操作吗?我在 Whosebug 上找到了 this 个答案。但我想也许 git 对此有更好的解决方案。

我在这里总结了你的问题:

Is there a way to push specified files in the .gitignore file to origin without adding and committing the excluded files?

很遗憾,没有。您可以 git add --force 需要的文件然后推送它,但这不是您要求的。

如果您尝试设置需要 API 密钥或其他机密的项目,我建议在项目的 README.md 文件中包含有关如何获取它们的说明。

不,没有。文件要么被 Git 跟踪,要么不被跟踪。

听起来您正在尝试创建某种被跟踪但被忽略的文件,而 Git 无法做到这一点。 Git FAQ explains why,并建议配置文件采用这种方法:

If your goal is to modify a configuration file, it can often be helpful to have a file checked into the repository which is a template or set of defaults which can then be copied alongside and modified as appropriate. This second, modified file is usually ignored to prevent accidentally committing it.

您可以使用脚本或作为构建过程的一部分执行此操作,以最适合您的项目的方式执行。

从技术上讲,可以在不提交的情况下将一个或多个文件推送到远程。以忽略的文件foo.txt为例:

git tag xxx $(git hash-object -w foo.txt) -m "Track the content of foo.txt"
git push origin xxx

它创建一个指向存储 foo.txt 内容的 blob 对象的标记,并将其推送到远程存储库。可以通过标签获取 blob 并读取内容。但是,如果没有额外的说明,就无法知道如何使用这些内容。