Mercurial 프로젝트에 빈 폴더를 추가하는 방법은 무엇입니까?


42

내 프로젝트에서는 사용자가 파일을 업로드 할 수있을 때 Mercurial과 폴더를 사용하고 있습니다. 그러나 사용자가 파일을 업로드하기 때문에 폴더가 비어 있습니다.

파일을 안에 넣지 않고 프로젝트에이 폴더를 어떻게 추가 할 수 있는지 모르겠습니다.

내가 어떻게 할 수 있는지 아니?

답변:


44

Mercurial은 계속 추적합니다. 파일들 , 디렉토리가 아님 .

한 가지 해결책은 .empty 파일을 저장소에 추가하는 것입니다.

$ touch uploads/.empty
$ hg add uploads/.empty

1
그렇습니다, 그것은 실제로 정확한 해결책입니다 : Mercurial은 파일들 , 아닙니다 디렉토리. 또 다른 솔루션은 소프트웨어를 배포 할 때 빈 디렉터리를 만드는 것입니다.
— Martin Geisler

2
나는 그것의 이름을 짓는 것을 생각하고있다. .hgempty 그것이 무엇을 위해 더 좋은 단서를 줄지도 모릅니다.
— User

6
예 또는 .hgkeep
— Natim

2
verbose로 갈 수도 있습니다 : .hgkeepifempty :)
— Daniel Sokolowski

4

나는 그 파일들을 생성 / 삭제하는 과정을 자동화하는 파이썬 스크립트를 만들었다.

스크립트의 소스는 다음과 같습니다. http://pastebin.com/inbYmMut

#!/usr/bin/python

# Copyright (c) 2011 Ernesto Mendez (der-design.com)
# Dual licensed under the MIT and GPL licenses:
# http://www.opensource.org/licenses/mit-license.php
# http://www.gnu.org/licenses/gpl.html

# Version 1.0.0
# - Initial Release

from __future__ import generators
import sys
from optparse import OptionParser
import os

def main():
    # Process arguments

    if len(args) > 1:
        parser.error('Too many arguments')
        sys.exit()

    elif len(args) == 0:
        parser.error('Missing filename')
        sys.exit()

    if not os.path.exists(options.directory):
        parser.error("%s: No such directory" % options.directory)
        sys.exit()

    filename = args[0]

    # Create generator

    filetree = dirwalk(os.path.abspath(options.directory))

    # Walk directory tree, create files

    if options.remove == True:

        removed = ['Removing the following files: \n']
        cmd = "rm"

        for file in filetree:
            if (os.path.basename(file) == filename):
                removed.append(file)
                cmd += " %s" % fixpath(file)

        if cmd != "rm":
            for f in removed: print f
            os.system(cmd)
        else:
            print "No files named '%s' found" % filename
            sys.exit()

    # Walk directory tree, delete files

    else:

        created = ["Creating the following files:\n"]
        cmd = "touch"

        for file in filetree:
            if (os.path.isdir(file)):
                created.append("%s%s" % (file, filename))
                cmd += " " + fixpath("%s%s" % (file, filename))

        if cmd != "touch":
            for f in created: print f
            os.system(cmd)
        else:
            print "No empty directories found"
            sys.exit()


def dirwalk(dir, giveDirs=1):
    # http://code.activestate.com/recipes/105873-walk-a-directory-tree-using-a-generator/
    for f in os.listdir(dir):
        fullpath = os.path.join(dir, f)
        if os.path.isdir(fullpath) and not os.path.islink(fullpath):
            if not len(os.listdir(fullpath)):
                yield fullpath + os.sep
            else:
                for x in dirwalk(fullpath):  # recurse into subdir
                    if os.path.isdir(x):
                        if giveDirs:
                            yield x
                    else:
                        yield x
        else:
            yield fullpath


def wrap(text, width):
    return reduce(lambda line, word, width=width: '%s%s%s' % (line, ' \n'[(len(line)-line.rfind('\n')-1 + len(word.split('\n', 1)[0] ) >= width)], word), text.split(' ') )


def fixpath(p):
    return shellquote(os.path.normpath(p))


def shellquote(s):
    return "'" + s.replace("'", "'\\''") + "'"


def init_options():
    global parser, options, args
    parser = OptionParser(usage="usage: %prog [options] filename", description="Add or Remove placeholder files for SCM (Source Control Management) tools that do not support empty directories.")
    parser.add_option("-p", "--path", dest="directory", help="search within PATH", metavar="PATH")
    parser.add_option("-r", "--remove", dest="remove", action="store_true", help="remove FILE from PATH, if it's the only file on PATH")

    (options, args) = parser.parse_args()

if __name__ == '__main__':
    print
    init_options()
    main()
    print

링크가 죽었습니다.
— Natim

True, 업데이트 된 링크 ...
— mendezcode

2
bitbucket (또는) github에서 호스트, 오래된 페이스트 인이 오래되었습니다.
— Phyo Arkar Lwin

-1, 그 스크립트는 nti 패턴과 나쁜 습관을 보여줍니다.
— Nikratio

1

다음과 같이하면됩니다.

mkdir images && touch images/.hgkeep
hg add images/.hgkeep
hg commit -m"Add the images folder as an empty folder"

다음을 고려할 때 다음 사항을 고려하십시오.

귀하의 경우에는 개발 환경에서 이미지를 업로드 할 수 있으므로 귀하의 컴퓨터에 다음을 추가하는 것이 좋습니다. .hgignore 파일을 사용하여 커밋하지 않을 이미지를 실수로 저 지르지 않도록합니다.

^(images)\/(?!\.hgkeep)

규칙은 모든 것을 무시합니다. images/** 제외하고 .hgkeep 파일을 "빈"폴더를 버전 제어에 추가해야합니다. 이 규칙이 중요한 이유는 해당 폴더에있는 모든 파일 (예 : images/test-image.png 버전이없는 새로운 파일처럼 보입니다. hg status 그 패턴을 무시하지 않으면.


2
질문을 다시 읽으십시오. 당신의 대답은 아니 "빈 폴더를 추가하는 방법"이 아니라 "폴더를 무시하는 방법"을 묻는 원래 질문에 대답하십시오.
— DavidPostill

1
네가 옳아. 실제로 답변에 대한 답변을 업데이트했습니다. 나는 충고를 바꿨으며, 99 %의 시간이 원하는 행동을 아는 것이 중요하기 때문에 떠났다.
— Paul Redmond

@ 폴루드먼 만약 있다면 images 경로의 깊숙한 디렉토리입니까? 좋아요. ./lectures/chapter_10/images? 그러면 올바른 구문은 무엇입니까?
— aaragon

@aaragon은 Mercurial을 사용한 이후로 꽤 오랜 시간이 걸렸지 만 의도 한 패턴과 일치하도록 정규식을 조정해야합니다. 무시할 것으로 예상되는 경로를 알게되면 필요에 따라 정규식을 조정하십시오.
— Paul Redmond
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.