One place for hosting & domains

      How To Use Git to Manage Your Writing Project


      Introduction

      Version control isn’t just for code. It’s for anything you want to track, including content. Using Git to manage your next writing project gives you the ability to view multiple drafts at the same time, see differences between those drafts, and even roll back to a previous version. And if you’re comfortable doing so, you can then share your work with others on GitHub or other central Git repositories.

      In this tutorial you’ll use Git to manage a small Markdown document. You’ll store an initial version, commit it, make changes, view the difference between those changes, and review the previous version. When you’re done, you’ll have a workflow you can apply to your own writing projects.

      Prerequisites

      Step 1 — Creating a Workspace for Your Writing Project

      To manage your changes, you’ll create a local Git repository. A Git repository lives inside of an existing directory, so start by creating a new directory for your article:

      Switch to the new article directory:

      The git init command creates a new empty Git repository in the current directory. Execute that command now:

      You’ll see the following output which confirms your repository was created:

      Output

      Initialized empty Git repository in /Users/sammy/article/.git/

      The .gitignore file lets you tell Git that some files should be ignored. You can use this to ignore temporary files your text editor might create, or operating systems files. On macOS, for example, the Finder application creates .DS_Store files in directories. Create a .gitignore file that ignores them:

      Add the following lines to the file:

      .gitignore

      # Ignore Finder files
      .DS_store
      

      The first line is a comment, which will help you identify what you’re ignoring in the future. The second line specifies the file to ignore.

      Save the file and exit the editor.

      As you discover more files you want to ignore, open the .gitignore file and add a new line for each file or directory you want to ignore.

      Now that your repository is configured, you can start working.

      Step 2 — Saving Your Initial Draft

      Git only knows about files you tell it about. Just because a file exists in the directory holding the repository doesn’t mean Git will track its changes. You have to add a file to the repository and then commit the changes.

      Create a new Markdown file called article.md:

      Add some text to the file:

      article.md

      # How To Use Git to Manage Your Writing Project
      
      ### Introduction
      
      Version control isn't just for code. It's for anything you want to track, including content. Using Git to manage your next writing project gives you the ability to view multiple drafts at the same time,  see differences between those drafts, and even roll back to a previous version. And if you're comfortable doing so, you can then share your work with others on GitHub or other central git repositories.
      
      In this tutorial you'll use Git to manage a small Markdown document. You'll store an initial version, commit it, make changes, view the difference between those changes, and review the previous version. When you're done, you'll have a workflow you can apply to your own writing projects.
      

      Save the changes and exit the editor.

      The git status command will show you the state of your repository. It will show you what files need to be added so Git can track them. Run this command:

      You’ll see this output:

      Output

      On branch master No commits yet Untracked files: (use "git add <file>..." to include in what will be committed) .gitignore article.md nothing added to commit but untracked files present (use "git add" to track)

      In the output, the Untracked files section shows the files that Git isn’t looking at. These files need to be added to the repository so Git can watch them for changes. Use the git add command to do this:

      • git add .gitignore
      • git add article.md

      Now run git status to verify those files have been added:

      Output

      On branch master No commits yet Changes to be committed: (use "git rm --cached <file>..." to unstage) new file: .gitignore new file: article.md

      Both files are now listed in the Changes to be committed section. Git knows about them, but it hasn’t created a snapshot of the work yet. Use the git commit command to do that.

      When you create a new commit, you need to provide a commit message. A good commit message states what your changes are. When you’re working with others, the more detailed your commit messages are, the better.

      Use the command git commit to commit your changes:

      • git commit -m "Add gitignore file and initial version of article"

      The output of the command shows that the files were committed:

      Output

      [master (root-commit) 95fed84] Add gitignore file and initial version of article 2 files changed, 9 insertions(+) create mode 100644 .gitignore create mode 100644 article.md

      Use the git status command to see the state of the repository:

      The output shows there are no changes that need to be added or committed.

      Output

      On branch master nothing to commit, working tree clean

      Now let’s look at how to work with changes.

      Step 3 — Saving Revisions

      You’ve added your initial version of the article. Now you’ll add more text so you can see how to manage changes with Git.

      Open the article in your editor:

      Add some more text to the end of the file:

      ## Prerequisites
      
      * Git installed on your local computer. The tutorial [How to Contribute to Open Source: Getting Started with Git](https://www.digitalocean.com/community/tutorials/how-to-contribute-to-open-source-getting-started-with-git) walks you through installing Git and covers some background information you may find useful. 
      

      Save the file.

      Use the git status command to see where things stand in your repository:

      The output shows there are changes:

      Output

      On branch master Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) modified: article.md no changes added to commit (use "git add" and/or "git commit -a")

      As expected, the article.md file has changes.

      Use git diff to see what they are:

      The output shows the lines you’ve added:

      diff --git a/article.md b/article.md
      index 77b081c..ef6c301 100644
      --- a/article.md
      +++ b/article.md
      @@ -5,3 +5,7 @@
       Version control isn't just for code. It's for anything you want to track, including content. Using Git to manage your next writing project gives you the ability to view multiple drafts at the same time,  see differences between those drafts, and even roll back to a previous version. And if you're comfortable doing so, you can then share your work with others on GitHub or other central git repositories.
      
       In this tutorial you'll use Git to manage a small Markdown document. You'll store an initial version, commit it, make changes, view the difference between those changes, and review the previous version. When you're done, you'll have a workflow you can apply to your own writing projects.
      +
      +## Prerequisites
      +
      +* Git installed on your local computer. The tutorial [How to Contribute to Open Source: Getting Started with Git](https://www.digitalocean.com/community/tutorials/how-to-contribute-to-open-source-getting-started-with-git) walks you through installing Git and covers some background information you may find useful. 
      

      In the output, lines starting with a plus (+) sign are lines you added. Lines that were removed would show up with a minus (-) sign. Lines that were unchanged would have neither of these characters in front.

      Using git diff and git status is a helpful way to see what you’ve changed. You can also save the diff to a file so you can view it later with the following command:

      • git diff article.md > article_diff.diff

      Using the .diff extension will help your text editor apply the proper syntax highlighting.

      Saving the changes to your repository is a two-step process. First, add the article.md file again, and then commit. Git wants you to explicitly tell it which files go in every commit, so even though you added the file before, you have to add it again. Note that the output from the git status command reminds you of that.

      Add the file and then commit the changes, providing a commit message:

      • git add article.md
      • git commit -m "add prerequisites section"

      The output verifies that the commit worked:

      Output

      [master 1fbfc21] add prerequisites section 1 file changed, 4 insertions(+)

      Use git status to see your repository status. You’ll see that there’s nothing else to do.

      Output

      On branch master nothing to commit, working tree clean

      Continue this process as you revise your article. Make changes, verify them, add the file, and commit the changes with a detailed message. Commit your changes as often or as little as you feel comfortable. You might perform a commit after you finish each draft, or right before you do a major rework of your article’s structure.

      If you send a draft of a document to someone else and they make changes to it, take their copy and replace your file with theirs. Then use git diff to see the changes they made quickly. Git will see the changes whether you typed them in directly or replaced the file with one you downloaded from the web, email, or elsewhere.

      Now let’s look at managing the versions of your article.

      Step 4 — Managing Changes

      Sometimes it’s helpful to look at a previous version of a document. Whenever you’ve used git commit, you’ve supplied a helpful message that summarizes what you’ve done.

      The git log command shows you the commit history of your repository. Every change you’ve committed has an entry in the log.

      Output

      commit 1fbfc2173f3cec0741e0a6b21803fbd0be511bc4 Author: Sammy Shark <sammy@digitalocean> Date: Thu Sep 19 16:35:41 2019 -0500 add prerequisites section commit 95fed849b0205c49eda994fff91ec03642d59c79 Author: Sammy Shark <sammy@digitalocean> Date: Thu Sep 19 16:32:34 2019 -0500 Add gitignore file and initial version of article

      Each commit has a specific identifier. You use this number to reference a specific commit’s changes. You only need the first several characters of the identifier though. The git log --oneline command gives you a condensed version of the log with shorter identifiers:

      Output

      1fbfc21 add prerequisites section 95fed84 Add gitignore file and initial version of article

      To view the initial version of your file, use git show and the commit identifier. The identifiers in your repository will be different than the ones in these examples.

      • git show 95fed84 article.md

      The output shows the commit detail, as well as the changes that happened during that commit:

      Output

      commit 95fed849b0205c49eda994fff91ec03642d59c79 Author: Sammy Shark <sammy@digitalocean> Date: Thu Sep 19 16:32:34 2019 -0500 Add gitignore file and initial version of article diff --git a/article.md b/article.md new file mode 100644 index 0000000..77b081c --- /dev/null +++ b/article.md @@ -0,0 +1,7 @@ +# How To Use Git to Manage Your Writing Project + +### Introduction + +Version control isn't just for code. It's for anything you want to track, including content. Using Git to manage your next writing project gives you the ability to view multiple drafts at the same time, see differences between those drafts, and even roll back to a previous version. And if you're comfortable doing so, you can then share your work with others on GitHub or other central git repositories. + +In this tutorial you'll use Git to manage a small Markdown document. You'll store an initial version, commit it, make changes, view the difference between those changes, and review the previous version. When you're done, you'll have a workflow you can apply to your own writing projects.

      To see the file itself, modify the command slightly. Instead of a space between the commit identifier and the file, replace with :./ like this:

      • git show 95fed84:./article.md

      You’ll see the content of that file, at that revision:

      Output

      # How To Use Git to Manage Your Writing Project ### Introduction Version control isn't just for code. It's for anything you want to track, including content. Using Git to manage your next writing project gives you the ability to view multiple drafts at the same time, see differences between those drafts, and even roll back to a previous version. And if you're comfortable doing so, you can then share your work with others on GitHub or other central git repositories. In this tutorial you'll use Git to manage a small Markdown document. You'll store an initial version, commit it, make changes, view the difference between those changes, and review the previous version. When you're done, you'll have a workflow you can apply to your own writing projects.

      You can save that output to a file if you need it for something else:

      • git show 95fed84:./article.md > old_article.md

      As you make more changes, your log will grow, and you’ll be able to review all of the changes you’ve made to your article over time.

      Conclusion

      In this tutorial you used a local Git repository to track the changes in your writing project. You can use this approach to manage individual articles, all the posts for your blog, or even your next novel. And if you push your repository to GitHub, you can invite others to help you edit your work.



      Source link

      How To Install Git on Debian 10


      Introduction

      Software version control systems like Git enable you to keep track of your software at the source level. With versioning tools, you can track changes, revert to previous stages, and branch to create alternate versions of files and directories.

      As one of the most popular version control systems currently available, Git is a common choice among open-source and other collaborative software projects. Many projects’ files are maintained in a Git repository, and sites like GitHub, GitLab, and Bitbucket help to facilitate software development project sharing and collaboration.

      In this tutorial, we’ll install and configure Git on a Debian 10 server. We will cover how to install the software in two different ways, each of which have their own benefits depending on your specific needs.

      Prerequisites

      In order to complete this tutorial, you should have a non-root user with sudo privileges on an Debian 10 server. To learn how to achieve this setup, follow our Debian 10 initial server setup guide.

      With your server and user set up, you are ready to begin. Jump to Installing Git with Default Packages (via the apt package manager) or Installing Git from Source to begin.

      Installing Git with Default Packages

      Debian’s default repositories provide you with a fast method to install Git. Note that the version you install via these repositories may be older than the newest version currently available. If you need the latest release, consider moving to the next section of this tutorial to learn how to install and compile Git from source.

      First, use the apt package management tools to update your local package index. With the update complete, you can download and install Git:

      • sudo apt update
      • sudo apt install git

      You can confirm that you have installed Git correctly by running the following command:

      Output

      git version 2.20.1

      With Git successfully installed, you can now move on to the Setting Up Git section of this tutorial to complete your setup.

      Installing Git from Source

      A more flexible method of installing Git is to compile the software from source. This takes longer and will not be maintained through your package manager, but it will allow you to download the latest release and will give you some control over the options you include if you wish to customize.

      Before you begin, you need to install the software that Git depends on. This is all available in the default repositories, so we can update our local package index and then install the packages.

      • sudo apt update
      • sudo apt install make libssl-dev libghc-zlib-dev libcurl4-gnutls-dev libexpat1-dev gettext unzip

      After you have installed the necessary dependencies, you can go ahead and get the version of Git you would like to install by visiting the Git project’s mirror on GitHub, available via the following URL:

      https://github.com/git/git
      

      From here, be sure that you are on the master branch. Click on the Tags link and select your desired Git version. Unless you have a reason for downloading a release candidate version (marked as rc), try to avoid these as they may be unstable.

      git change branch select tags

      Next, on the right side of the page, click on the Clone or download button, then right-click on Download ZIP and copy the link address that ends in .zip.

      right-click on download zip to copy url

      Back on your Debian 10 server, move into the tmp directory to download temporary files.

      From there, you can use the wget command to install the copied zip file link. We’ll specify a new name for the file: git.zip.

      • wget https://github.com/git/git/archive/v2.23.0.zip -O git.zip

      Unzip the file that you downloaded and move into the resulting directory by typing:

      Now, you can make the package and install it by typing these two commands:

      • make prefix=/usr/local all
      • sudo make prefix=/usr/local install

      To ensure that the install was successful, you can type git --version and you should receive relevant output that specifies the current installed version of Git.

      Now that you have Git installed, if you want to upgrade to a later version, you can clone the repository, and then build and install. To find the URL to use for the clone operation, navigate to the branch or tag that you want on the project’s GitHub page and then copy the clone URL on the right side:

      git copy URL

      At the time of writing, the relevant URL is:

      https://github.com/git/git.git
      

      Change to your home directory, and use git clone on the URL you just copied:

      • cd ~
      • git clone https://github.com/git/git.git

      This will create a new directory within your current directory where you can rebuild the package and reinstall the newer version, just like you did above. This will overwrite your older version with the new version:

      • cd git
      • make prefix=/usr/local all
      • sudo make prefix=/usr/local install

      With this complete, you can be sure that your version of Git is up to date.

      Setting Up Git

      Now that you have Git installed, you should configure it so that the generated commit messages will contain your correct information.

      This can be achieved by using the git config command. Specifically, we need to provide our name and email address because Git embeds this information into each commit we do. We can go ahead and add this information by typing:

      • git config --global user.name "Sammy"
      • git config --global user.email "sammy@domain.com"

      We can see all of the configuration items that have been set by typing:

      Output

      user.name=Sammy user.email=sammy@domain.com

      The information you enter is stored in your Git configuration file, which you can optionally edit by hand with a text editor like this:

      ~/.gitconfig contents

      [user]
        name = Sammy
        email = sammy@domain.com
      

      There are many other options that you can set, but these are the two essential ones needed. If you skip this step, you’ll likely see warnings when you commit to Git. This makes more work for you because you will then have to revise the commits you have done with the corrected information.

      Conclusion

      You should now have Git installed and ready to use on your system.

      To learn more about how to use Git, check out these articles and series:

      Additionally, you can learn more by reviewing our series on An Introduction to Open Source for more information about using Git as part of open-source projects.



      Source link

      Como Instalar o Git no CentOS 7


      Introdução

      O controle de versão tornou-se uma ferramenta indispensável no desenvolvimento de software moderno. Os sistemas de controle de versão permitem que você mantenha o controle do seu software no nível do código-fonte. Você pode acompanhar as alterações, reverter para os estágios anteriores e fazer a ramificação ou branching do código base para criar versões alternativas de arquivos e diretórios.

      Um dos sistemas de controle de versão mais populares é o git. Muitos projetos mantêm seus arquivos em um repositório Git, e sites como o GitHub e o Bitbucket tornaram o compartilhamento e a contribuição para o código com o Git mais fácil do que nunca.

      Neste guia, demonstraremos como instalar o Git em um servidor do CentOS 7. Vamos abordar como instalar o software de duas maneiras diferentes, cada uma com seus próprios benefícios, além de como configurar o Git para que você possa começar a colaborar imediatamente.

      Pré-requisitos

      Antes de começar com este guia, há algumas etapas que precisam ser concluídas primeiro.

      Você precisará de um servidor CentOS 7 instalado e configurado com um usuário não-root que tenha privilégios sudo. Se você ainda não fez isso, você pode executar os passos de 1 a 4 no guia de Configuração Inicial do Servidor com CentOS 7 para criar essa conta.

      Depois de ter seu usuário não-root, você pode usá-lo para fazer SSH em seu servidor CentOS e continuar com a instalação do Git.

      Instalar o Git

      As duas formas mais comuns de instalar o Git serão descritas nesta seção. Cada opção tem suas próprias vantagens e desvantagens, e a escolha que você fizer dependerá de suas próprias necessidades. Por exemplo, os usuários que desejam manter atualizações para o software Git provavelmente vão querer usar o yum para instalá-lo, enquanto os usuários que precisam de recursos apresentados por uma versão específica do Git vão querer construir essa versão a partir do código-fonte.

      Opção Um — Instalar o Git com Yum

      A maneira mais fácil de instalar o Git e tê-lo pronto para usar é utilizar os repositórios padrão do CentOS. Este é o método mais rápido, mas a versão do Git que é instalada dessa forma pode ser mais antiga que a versão mais recente disponível. Se você precisa da versão mais recente, considere compilar o git a partir do código-fonte (as etapas para este método podem ser encontradas mais abaixo neste tutorial).

      Use o yum, gerenciador de pacotes nativo do CentOS, para procurar e instalar o pacote git mais recente disponível nos repositórios do CentOS:

      sudo yum install git
      

      Se o comando for concluído sem erro, você terá o git baixado e instalado. Para verificar novamente se ele está funcionando corretamente, tente executar a verificação de versão integrada do Git:

      git --version
      

      Se essa verificação produziu um número de versão do Git, você pode agora passar para Configurando o Git, encontrado mais abaixo neste artigo.

      Opção Dois — Instalar o Git a Partir do Código-fonte

      Se você deseja baixar a versão mais recente do Git disponível, ou simplesmente deseja mais flexibilidade no processo de instalação, o melhor método para você é compilar o software a partir do código-fonte. Isso leva mais tempo, e não será atualizado e mantido através do gerenciador de pacotes yum, mas permitirá que você baixe uma versão mais recente do que a que está disponível através dos repositórios do CentOS, e lhe dará algum controle sobre as opções que você pode incluir.

      Antes de começar, você precisará instalar o software do qual o git depende. Estas dependências estão todas disponíveis nos repositórios padrão do CentOS, junto com as ferramentas que precisamos para construir um binário a partir do código-fonte:

      sudo yum groupinstall "Development Tools"
      sudo yum install gettext-devel openssl-devel perl-CPAN perl-devel zlib-devel
      

      Depois de ter instalado as dependências necessárias, você pode ir em frente e procurar a versão do Git que você deseja, visitando a página de releases do projeto no GitHub.

      Git Releases on GitHub

      A versão no topo da lista é a versão mais recente. Se ela não tiver um -rc (abreviação de “Release Candidate”) no nome, isso significa que é uma versão estável e segura para uso. Clique na versão que você deseja baixar para acessar a página de release dessa versão. Em seguida, clique com o botão direito do mouse no botão Source code (tar.gz) e copie o link para a sua área de transferência.

      Copy Source Code Link

      Agora vamos usar o comando wget em nosso servidor CentOS para baixar o arquivo fonte do link que copiamos, renomeando-o para git.tar.gz no processo, para que seja mais fácil trabalhar com ele.

      Nota: a URL que você copiou pode ser diferente da minha, pois a versão que você baixou pode ser diferente.

      wget https://github.com/git/git/archive/v2.1.2.tar.gz -O git.tar.gz
      

      Quando o download estiver concluído, podemos descompactar o arquivo fonte usando o tar. Vamos precisar de algumas flags extras para garantir que a descompactação seja feita corretamente: z descompacta o arquivo (já que todos os arquivos .gz são compactados), x extrai os arquivos e pastas individuais do arquivo, e f diz ao tar que estamos declarando um nome de arquivo para trabalhar.

      tar -zxf git.tar.gz
      

      Isto irá descompactar o código-fonte compactado para uma pasta com o nome da versão do Git que baixamos (neste exemplo, a versão é 2.1.2, então a pasta é nomeada como git-2.1.2). Precisamos nos mover para essa pasta para começar a configurar nossa compilação. Em vez de nos preocuparmos com o nome completo da versão na pasta, podemos usar um caractere curinga (*) para nos poupar de algum problema ao mudar para essa pasta.

      cd git-*
      

      Uma vez que estivermos na pasta de fontes, podemos começar o processo de compilação. Isso começa com algumas verificações de pré-compilação para coisas como dependências de software e configurações de hardware. Podemos verificar tudo o que precisamos com o script configure gerado pelo make configure. Este script também usará um --prefix para declarar /usr/local (a pasta padrão do programa para plataformas Linux) como o destino apropriado para o novo binário, e criará um Makefile para ser usado no passo seguinte.

      make configure
      ./configure --prefix=/usr/local
      

      Makefiles são arquivos de configuração de script que são processados pelo utilitário make. Nosso Makefile dirá ao make como compilar um programa e vinculá-lo à nossa instalação do CentOS, para que possamos executar o programa corretamente. Com um Makefile pronto, agora podemos executar make install (com privilégios sudo) para compilar o código-fonte em um programa funcional e instalá-lo em nosso servidor:

      sudo make install
      

      O Git deve agora ser compilado e instalado em seu servidor CentOS 7. Para verificar novamente se está funcionando corretamente, tente executar a verificação de versão integrada do Git:

      git --version
      

      Se essa verificação produziu um número de versão do Git, então você pode passar para Configurando o Git abaixo.

      Configurando o Git

      Agora que você tem o git instalado, você precisará enviar algumas informações sobre si mesmo para que as mensagens de commit sejam geradas com as informações corretas anexadas. Para fazer isso, use o comando git config para fornecer o nome e o endereço de e-mail que você gostaria de ter registrado em seus commits:

      git config --global user.name "Seu Nome"
      git config --global user.email "voce@example.com"
      

      Para confirmar que essas configurações foram adicionadas com sucesso, podemos ver todos os itens de configuração que foram definidos, digitando:

      git config --list
      
      user.name=Seu Nome
      user.email=voce@example.com
      

      Essa configuração te poupará do trabalho de ver uma mensagem de erro e ter que revisar os commits após submetê-los.

      Conclusão

      Agora você deve ter o git instalado e pronto para uso em seu sistema. Para saber mais sobre como usar o Git, confira estes artigos mais detalhados:



      Source link