Copying Files

Mercurial provides a hg copy command that lets you make a new copy of a file. When you copy a file using this command, Mercurial makes a record of the fact that the new file is a copy of the original file. It treats these copied files specially when you merge your work with someone else’s.

The Results of Copying During a Merge

What happens during a merge is that changes follow a copy. To best illustrate what this means, let’s create an example. We’ll start with the usual tiny repository that contains a single file.

$ hg init my-copy
$ cd my-copy
$ echo line > file
$ hg add file
$ hg commit -m 'Added a file'

We need to do some work in parallel, so that we’ll have something to merge. So let’s clone our repository.

$ cd ..
$ hg clone my-copy your-copy
updating working directory
1 files updated, 0 files merged, 0 files removed, 0 files unresolved

Back in our initial repository, let’s use the hg copy command to make a copy of the first file we created.

$ cd my-copy
$ hg copy file new-file

If we look at the output of the hg status command afterwards, the copied file looks just like a normal added file.

$ hg status
A new-file

But if we pass the -C option to hg status, it prints another line of output: this is the file that our newly added file was copied from.

$ hg status -C
A new-file
  file
$ hg commit -m 'Copied file'

Now, back in the repository we cloned, let’s make a change in parallel. We’ll add a line of content to the original file that we created.

$ cd ../your-copy
$ echo 'new ...

Get Mercurial: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.