用RStudio与Git、GitHub连接起来,实现代码管理和数据分析
Git的基本操作以及如何通过RStudio与GitHub进行交互。这里仅介绍了通过Git和Rstudio管理GitHub仓库的设置步骤。更多内容见 https://happygitwithr.com/
配置Git
使用下面的命令查看Git的安装位置和版本。
1 | which git |
更新Git
1 | git update-git-for-windows |
设置Git用户名和邮件
1 | git config --global user.name "leafminer" |
也可以使用R包usethis
1 | library(usethis) |
设定默认的初始分支名为main
1 | git config --global init.defaultBranch main |
R包usethis
1 | # 默认为main |
设定令牌
R包usethis
1 | # 跳转到 https://github.com/settings/tokens,创建Token |
设定GitHub远程仓库和仓库地址
1 | git remote set-url 2024-R-PhDdata https://github.com/leafminer/2024-R-PhDdata.git |
R包usethis
1 | # 查看远程库和地址 |
credentials
和gh
包
1 | credentials::set_github_pat() |
设定密钥
1 | ssh-keygen -t rsa -b 4096 -C "Rstudio" |
确保ssh - agent处于运行状态:
1 | eval $(ssh-agent -s) |
添加你的密钥,用正确的名字代替你的钥匙。
1 | ssh-add ~/.ssh/id_rstudio |
复制公钥到剪贴板:
1 | clip < ~/.ssh/id_rstudio.pub |
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIA9kHA+/Vx8ksFibaRCYYlj2r/zS5DezRmSOsn00AltJ Rstudio
使用Git连接GitHub仓库
登录GitHub,添加公钥到远程仓库。步骤见https://blog.leafminer.cn/2024/11/30/b3793277a33f/
检验是否成功
1 | ssh -T git@github.com |
克隆远程仓库到本地
1 | git clone https://github.com/leafminer/2024-R-PhDdata.git |
使用Git上传本地文件到远程仓库
1 | git commit |
在Windows上,你可能会看到一个关于LF的消息会被CRLF所取代。这是正常的,不需要对你的部分采取任何行动。Windows对行结尾的处理与其他操作系统不同,但Git for Windows的默认设置适合大多数人和情况。
1 | git config --show-origin --get core.autocrlf |
使用Rstudio管理仓库
连接远程仓库
-
使用已有的仓库,或者创建新的仓库。通过
Add a README file
初始化仓库。复制下图的链接:
-
在Rstudio中创建新的项目:
File
> New Project
> Version Control
> Git
Repository URL粘贴上一步复制的仓库链接。
-
上述操作应该会自动从GitHub下载名为README.md的文件。表明本地与远程连接成功。
保存,更改和提交
点击右上方窗格中的" Git "选项卡。
或者
勾选文件旁边的“Staged
”(已暂存)复选框,表示你想要将这个文件的更改包含在即将进行的提交中。
如果你还没有在Git弹出窗口中,点击“Commit
”(提交)按钮。这将打开一个新的提交窗口。
输入提交信息:在提交窗口中,你需要输入一个“Commit message”(提交信息),这个信息简要描述了你所做的更改。在这个例子中,你可以输入“Commit from RStudio”来表示这个提交是在RStudio中完成的。
完成提交:输入完提交信息后,点击“Commit
”按钮来完成提交过程。这样,你的更改就会被保存到本地的Git仓库中。点击“Push
”推送到GitHub仓库。
参考
-
https://happygitwithr.com/ssh-keys
-
https://happygitwithr.com/push-pull-github