Subversion Mime Type Bininary Options
Para o plano de fundo na minha pergunta: svn não exibirá um arquivo que considere binário Uma resposta de transbordamento de pilha recente (svn diff: arquivo marcado como tipo binário) mostrou que você pode forçar um tipo mime: Observe que a resposta anterior está incompleta. Você também precisa: Agora, minha nova pergunta é: posso definir um padrão, então todos os futuros arquivos vnd. google-earth. kmlxml são tratados como texto por svn. O caderno vermelho aparece silencioso sobre este tópico: svnbook. red-beanen1.2svn. Advanced. props. html dizendo apenas: quais exceções Essas exceções são assadas no código svn ou acessíveis. A resposta depende do cliente svn que você está usando. No cliente svn oficial, a opção que você está procurando é a Configuração de Propriedade Automática. A versão tldr é necessário atualizar sua configuração do usuário ou do sistema. Defina a configuração enable-auto-props para yes na seção miscellany e crie uma nova seção chamada auto-props que define os padrões que deseja combinar e as propriedades que você deseja configurar. Para o seu exemplo de arquivos kml: Isso garantirá que, quando você adiciona um arquivo. kml ao seu repositório, ele terá um tipo de texto de mime e usará endereços de linha nativos da plataforma do cliente. Perguntas frequentes sobre o Subversion O que é o Subversion Por que isso existe para O Subversion é um sistema de controle de versão centralizado de código aberto. Veja Nossa Visão em nossa página inicial para saber por que o Subversion existe. Deseja dar uma olhada rápida Veja o Início Rápido. O software proprietário do Subversion para No, o Subversion é um software livre de código aberto. Várias empresas (CollabNet, WANdisco, VisualSVN, elego.) Pagam ou pagaram os salários de alguns desenvolvedores de tempo integral, mas o software possui uma Licença Apache que é totalmente compatível com as Diretrizes de Software Livre Debian. Em outras palavras, você é livre para baixar, modificar e redistribuir o Subversion, pois você não deseja permissão de nenhuma empresa ou qualquer pessoa é necessária. Quão estável é o Subversion para Subversion é muito estável. É software maduro, com fortes garantias de compatibilidade. A comunidade de desenvolvimento do Subversion se preocupa profundamente com sua estabilidade e robustez. O Subversion está em desenvolvimento desde 2000 e se tornou auto-hospedado após um ano. Um ano depois, quando declaramos alfa, o Subversion já estava sendo usado por dezenas de desenvolvedores privados e lojas para o trabalho real. Depois disso, foram mais dois anos de bugfixing e estabilização até atingir 1,0. A maioria dos outros projetos provavelmente teria chamado o produto 1,0 muito mais cedo, mas deliberadamente decidimos atrasar esse rótulo o maior tempo possível. Estávamos conscientes de que muitas pessoas estavam esperando por um 1.0 antes de usar o Subversion e tinham expectativas muito específicas sobre o significado desse rótulo. Então ficamos com esse mesmo padrão. O que é a política de interoperabilidade do cliente do Subversions para o cliente e o servidor são projetados para funcionar enquanto não forem mais de uma versão de lançamento principal. Por exemplo, qualquer cliente 1.X funcionará com um servidor 1.Y. No entanto, se as versões do cliente e do servidor não coincidem, alguns recursos podem não estar disponíveis. Tais limitações são sempre documentadas nas notas de lançamento de nossos lançamentos. Nossa política de interoperabilidade do servidor de clientes está documentada na seção de Compatibilidade do Guia da Comunidade do Subversion. Quais sistemas operacionais o Subversion é executado em para Todos os sabores modernos do Unix, Win32, BeOS, OS2, MacOS X. O Subversion está escrito em ANSI C e usa APR, a biblioteca Apache Portable Runtime, como uma camada de portabilidade. O cliente do Subversion será executado em qualquer lugar, o que é a maioria dos lugares. O servidor Subversion (ou seja, o lado do repositório) é o mesmo, exceto que ele não hospedará um banco de dados Berkeley DB em plataformas Win9x (Win95Win98WinME), porque o Berkeley DB possui problemas de segmento de memória compartilhada no Win9x. Os repositórios FSFS (introduzidos na versão 1.1) não possuem essa restrição no entanto, devido a uma limitação no suporte ao bloqueio de arquivos Win9xs, eles também não funcionam no Win9x. Para reiterar, o cliente do Subversion pode ser executado em qualquer plataforma onde o APR seja executado. O servidor Subversion também pode ser executado em qualquer plataforma onde o APR é executado, mas não pode hospedar um repositório no Win95Win98WinMe. O que é tudo sobre um novo sistema de arquivos É como ext2 para No. O sistema de arquivos do Subversion não é um sistema de arquivos do nível do kernel que seria instalado em um sistema operacional. Em vez disso, é a interface do repositório Subversions, que é um sistema de arquivos versionado, no sentido de que ele armazena uma árvore de diretórios cujo estado é lembrado de revisão para revisão. Escrever programas para acessar o repositório é semelhante aos programas de escrita que usam outras APIs do sistema de arquivos. A principal diferença é que este sistema de arquivos particular não perde dados quando gravados em estados de árvore anteriores pode ser recuperado com facilidade o estado mais recente. Que tipo de hardware preciso para executar um servidor Subversion para Os requisitos do servidor dependem de muitos fatores, como número de usuários, freqüência de compromissos e outras operações relacionadas ao servidor, o tamanho do repositório e a carga gerada pelos ganchos de repositório personalizados. Ao usar o Apache, é provável que o próprio Apache seja o maior fator no uso da memória. Lembre-se de levar em conta outros aplicativos executados no mesmo servidor, por exemplo, os navegadores de repositório usam recursos também, independentemente do próprio Subversion. Em geral, você pode esperar precisar de muito menos memória do servidor do que você faria para repositórios CVS comparáveis. Ouvi dizer que o Subversion é uma extensão do Apache O que ele usa para os servidores para o No. Subversion é um conjunto de bibliotecas. Ele vem com um cliente de linha de comando que os usa. Existem dois processos diferentes do servidor Subversion: ou svnserve. Que é um pequeno programa autônomo semelhante ao cvs pserver ou o Apache httpd-2.0 usando um módulo especial moddavsvn. Svnserve fala um protocolo personalizado, enquanto o moddavsvn usa WebDAV como seu protocolo de rede. Veja o capítulo 6 no livro do Subversion para saber mais. Isso significa que eu tenho que configurar o Apache para usar o Subversion para A resposta curta: não. A resposta longa: se você quiser apenas acessar um repositório, então você só precisa criar um cliente do Subversion. Se você quiser hospedar um repositório em rede, então você precisa configurar o Apache2 ou o servidor svnserve. Para obter mais detalhes sobre como configurar um servidor Subversion acessível pela rede, consulte o capítulo 6 no livro do Subversion. Executo o Apache 1.x no momento, e não posso mudar para o Apache 2.0 apenas para servir os repositórios do Subversion. Isso significa que eu não posso executar um servidor Subversion para No, você pode executar o svnserve como um servidor Subversion. Funciona muito bem. Se você deseja WebDAV e todos os outros brindes que acompanham o servidor Apache, então sim, você precisará do Apache 2.0. É sempre uma opção para executar o Apache 2.0 em uma porta diferente enquanto continua a executar o Apache 1.x na porta 80. Diferentes versões do Apache podem coexistir feliz na mesma máquina. Basta alterar a diretiva Listen em httpd. conf de Listen 80 para Listen 8080 ou qualquer número de porta que você deseja, e certifique-se de especificar essa porta quando você publica o URL do repositório (por exemplo, svn. mydomain: 8080reposblahtrunk). Por que você não faz X, assim como o sistema SCM Y para Subversion não está tentando imitar todos os recursos de cada sistema SCM lá fora. Veja nossa visão. Por que todo o repositório compartilha o mesmo número de revisão, eu quero que cada um dos meus projetos tenha seus próprios números de revisão. Para Primeiro, note que o Subversion não possui nenhum conceito de projetos. O repositório apenas armazena um mdash de árvore de diretório versionado, você pode considerar que determinadas sub-árvores são projetos, mas o Subversion não os trata de maneira diferente de qualquer outra sub-árvore. Assim, a interpretação do que constitui um projeto no repositório é deixada inteiramente aos usuários. (Isto é semelhante à forma como ramos e tags são convenções construídas em cima de cópias, em vez de serem conceitos básicos incorporados no próprio Subversion). Cada vez que você comete uma alteração, o repositório armazena uma nova revisão dessa árvore geral do repositório e rotula o Nova árvore com um novo número de revisão. Claro, a maior parte da árvore é a mesma que a revisão anterior, exceto pelas partes que você mudou. O novo número de revisão é um rótulo seqüencial que se aplica a toda a nova árvore, não apenas aos arquivos e diretórios que você tocou nessa revisão. No entanto, de forma coloquial, um número de revisão é usado para se referir à mudança cometida nessa revisão, por exemplo, a alteração em r588 (r588 é uma abreviatura para a revisão 588) significa realmente a diferença entre as árvores de repositório 587 e 588, ou de outro modo, a Mudança feita para a árvore 587 para produzir a árvore 588. Assim, o número de revisão avançada marca o progresso do repositório como um todo, você geralmente não pode medir o progresso de um projeto específico dentro do repositório, observando o número da revisão. Além disso, o número da revisão não deve ser usado como o número de lançamento publicamente visível de um projeto específico no repositório. Para isso, você deve planejar algum outro mecanismo para distinguir lançamentos, como usar tags. Subversion tem Changesets para A questão é um pouco carregada, porque todos parecem ter uma definição ligeiramente diferente de changeset ou, pelo menos, uma expectativa ligeiramente diferente do que significa que um sistema de controle de versão tenha recursos do changeset. Para os propósitos desta discussão, ela possui uma simples definição de changeset: é uma coleção de mudanças com um nome exclusivo. As alterações podem incluir edições de texto para o conteúdo do arquivo, modificações na estrutura da árvore ou ajustes em metadados. Na fala mais comum, um conjunto de mudanças é apenas um patch com um nome ao qual você pode se referir. O Subversion gerencia as árvores versionadas como objetos de primeira ordem (o repositório é uma matriz de árvores) e os conjuntos de mudanças são coisas derivadas (comparando árvores adjacentes). Sistemas como o Arch ou o Bitkeeper são construídos ao contrário: eles foram projetados para gerenciar conjuntos de mudanças Como objetos de primeira ordem (o repositório é um saco de patches), e as árvores são derivadas compondo conjuntos de patches juntos. Nem a filosofia é melhor em termos absolutos: o debate remonta ao menos 30 anos. Os dois projetos são melhores ou pior para diferentes tipos de desenvolvimento de software. Não vamos discutir isso aqui. Em vez disso, há uma explicação sobre o que você pode fazer com o Subversion. No Subversion, um número de revisão global N nomeia uma árvore no repositório: é a forma como o repositório cuidou da confirmação Nth. É também o nome de um conjunto de mudanças implícitas: se você comparar a árvore N com a árvore N-1, você pode derivar o patch exato que foi cometido. Por esta razão, é fácil pensar na revisão N como não apenas uma árvore, mas também um conjunto de mudanças. Se você usa um rastreador de problemas para gerenciar erros, você pode usar os números de revisão para se referir a patches específicos que corrigem erros - por exemplo, esse problema foi corrigido pela revisão 9238. Alguém pode então executar svn log - r9238 para ler sobre o exato Conjunto de alterações que corrigiu o erro e execute svn diff - r9237: 9238 para ver o patch em si. E o comando svns merge também usa números de revisão. Você pode mesclar conjuntos de mudanças específicos de um ramo para outro, nomeando-os nos argumentos de mesclagem: svn merge - r9237: 9238 branchURL combinaria changeset 9238 em sua cópia de trabalho. Isso não é tão complicado quanto um sistema construído em torno de changesets como objetos primários, mas ainda é uma grande conveniência em relação ao CVS. Whens the next release para O Subversion suporta links simbólicos para Subversion 1.1 (e posterior) tem a capacidade de colocar um link simbólico (unix) sob controle de versão, através do comando usual svn add. Detalhes: o repositório do Subversion não possui um conceito interno de um link simbólico. Ele armazena um link simbólico de versão como um arquivo comum com um svn: propriedade especial anexada. O cliente svn (no unix) vê a propriedade e converte o arquivo em um link simbólico na cópia de trabalho. No Windows, o cliente svn atualmente não possui suporte para traduzir um link simbólico controlado em uma das variantes do Symlink do Windows (pontos de junção etc.). O objeto verificado aparece como um arquivo normal. Um dos problemas que tornam isso difícil de suportar em geral é que, por padrão, apenas os Administradores podem criar links simbólicos no Windows. Para obter mais informações, consulte o problema SVN-3570. Preciso de uma versão de alta resolução do logotipo do Subversion, onde posso obtê-lo para As versões vetadas do logotipo do Subversion estão disponíveis no diretório do logo da árvore do depósito do Subversion. Eu tenho outras perguntas. Onde posso obter mais informações para Se você não encontrar uma resposta depois de navegar nesta FAQ, existem vários outros recursos disponíveis: Por que minha postagem não aparece na lista de endereços para Nossas listas de endereços são moderadas para evitar que o spam seja superado, então você A primeira postagem em qualquer lista pode ser adiada, até que o moderador tenha a chance de passar. Uma vez que essa postagem é permitida, todas as postagens subseqüentes do mesmo endereço são aprovadas automaticamente, então você não deve experimentar mais demoras. Claro, se o seu endereço de envio mudar, então você terá que passar novamente pela moderação. Como o Subversion é afetado por alterações no horário de verão (DST) para Alterações para DST não requerem alterações ou correções especiais para o código Subversion. Subversion usa principalmente datastimes para gravar quando as alterações foram comprometidas com o repositório. Este código é executado no servidor e obtém o tempo atual da data do sistema operacional e o converte em UTC usando rotinas fornecidas pelo sistema operacional. O cliente Subversion recebe essas datas do servidor e converte-as para o fuso horário local para exibição usando rotinas fornecidas pelo sistema operacional cliente. Como tal, você só precisa instalar os patches fornecidos para o seu sistema operacional e, na verdade, você só precisa ter certeza de que o tempo no servidor esteja corretamente ajustado para DST. How-to: para Como faço para verificar o código Subversion para Usar o cliente Subversion: Isso verificará uma cópia da árvore de origem Subversion em um diretório chamado subversion em sua máquina local. Como faço para criar um repositório Como eu importo dados para ele Para Para mais detalhes sobre a configuração e administração do repositório, leia o capítulo 5 no Livro do Subversion. Como faço para converter um repositório CVS existente em um repositório Subversion para Experimente a ferramenta de conversão cvs2svn, de cvs2svn. tigris. org (veja também a lista de recursos e a documentação). Cvs2svn parece ser o que a maioria das pessoas usa, mas se, por algum motivo, não atender às suas necessidades, existem pelo menos duas outras ferramentas que você poderia tentar: e se eu estiver atrás de um proxy para O cliente do Subversion pode passar por um proxy, se você configurar Para fazê-lo. Primeiro, edite o arquivo de configuração dos seus servidores para indicar qual proxy usar. A localização dos arquivos depende do seu sistema operacional. No Linux ou no Unix, ele está localizado no diretório. subversion. No Windows está em APPDATASubversão. (Experimente o APPDATA, observe que este é um diretório oculto.) Há comentários no arquivo que explica o que fazer. Se você não possui esse arquivo, obtenha o último cliente do Subversion e execute qualquer comando, isso fará com que o diretório de configuração e os arquivos de modelo sejam criados. Em seguida, você precisa ter certeza de que o próprio servidor proxy suporte todos os métodos HTTP que o Subversion usa. Alguns servidores proxy não suportam esses métodos por padrão: PROPFIND, REPORT, MERGE, MKACTIVITY, CHECKOUT. Em geral, resolver isso depende do software proxy específico. Para Squid, a opção de configuração é (Squid 2.4 e versões posteriores já sabem sobre o PROPFIND.) Veja também Quais são todos os métodos HTTP que o Subversion usa para obter conselhos sobre métodos HTTP adicionais para permitir através do seu proxy. Se for difícil ou impossível obter o proxy para permitir o tráfego do Subversion, mas você deseja verificar as fontes do Subversion, você poderá percorrer o proxy. Alguns proxies que filtram a porta 80, no entanto, permitem qualquer coisa na porta 81. Em muitos outros casos, os proxies não filtram https tão rigorosos quanto eles filtram http. O servidor do repositório svn. apache. org escuta em https, bem como em http. Tente: e talvez o proxy o deixe passar. Claro, seu cliente svn terá que ter sido criado com suporte ssl. Você pode verificar se o esquema https é suportado executando svn --version. Meus administradores não querem que eu tenha um servidor HTTP para o Subversion. O que posso fazer se ainda quiser uso remoto? Uma opção simples é usar o servidor svnserve em vez do Apache. Consulte o capítulo 6 no livro do Subversion para obter detalhes. No entanto, se seus administradores não quiserem que você execute o Apache, é provável que eles não desejem que você execute um processo de servidor personalizado na porta 3690. Então, o resto dessa resposta assume que seus administradores estão bem com você usando uma infra-estrutura SSH existente. Se você já usou CVS, você pode ter usado o SSH para se conectar ao servidor CVS. O método de acesso Rasvn Subversion é a forma equivalente de fazer isso com o Subversion. Basta usar o prefixo svnssh para o URL do repositório do Subversion. Isso faz o seu programa SSH iniciar um processo svnserve privado na caixa remota, que acessa o repositório como seu UID e obstrui as informações de volta ao link criptografado. No entanto, outra solução que pode ser usada em vez disso é aproveitar o encaminhamento da porta SSH para se conectar ao servidor protegido via radav. Você se conectaria via SSH a uma máquina atrás do seu firewall que pode acessar seu servidor Subversion. Observe que este servidor SSH não precisa ser o mesmo que o Subversion está instalado. Pode ser, mas não precisa ser. Em seguida, você cria uma frente de porta local que se conecta ao servidor HTTP que abriga seu repositório Subversion. Você então se conectaria ao repositório do Subversion através desta porta local. Então, o pedido será enviado tunneled via servidor SSH para o seu servidor Subversion. Um exemplo: uma instalação do radav do Subversion está por trás do firewall da sua empresa em 10.1.1.50 (ligue para svn-server. example). Sua empresa permite o acesso SSH via ssh-server. example publicamente acessível. Internamente, você pode acessar o repositório do Subversion via svn-server. examplereposours. Exemplo. Cliente que se conecta ao servidor ssh com encaminhamento de porta e verificação via via portuária. Observe que o seu svn-server. example também poderia ter sua instância httpd executada em uma porta não privilegiada por um usuário não confiável. Isso permitirá que o servidor do Subversion não exija acesso a raiz. Joe Orton observa alguns links no encaminhamento de porta SSH Como gerenciar vários projetos diferentes no Subversion para Depende dos projetos envolvidos. Se os projetos estão relacionados e é provável que compartilhem dados, então é o melhor para criar um repositório com vários subdiretórios como este: Se os projetos estiverem completamente não relacionados e não é provável que compartilhem dados entre eles, provavelmente é melhor criar Repositórios não relacionados. A diferença entre essas duas abordagens é esta (como explicado por Ben Collins-Sussman ltsussmancollabgt): no primeiro caso, o código pode ser facilmente copiado ou movido entre projetos e o histórico é preservado. (Svn cpmv atualmente só funciona dentro de um único repositório.) Como os números de revisão são de todo o repositório, um commit em qualquer projeto no primeiro caso causa uma colisão de revisão global. Por isso, pode parecer um pouco estranho se alguém tiver registrado, percebe que 10 revisões aconteceram, mas o ProjB não mudou. Nada de mais, na verdade. Apenas um pouco estranho no começo. Isso costumava acontecer com Svn sempre que as pessoas se comprometeram com rapidsvn, quando o rapidsvn estava no mesmo repositório. -) O segundo caso pode ser mais fácil de garantir que seja mais fácil isolar projetos uns dos outros (em termos de usuários e permissões) usando o controle de acesso Apaches. No primeiro caso, você precisará de um script de gancho extravagante no repositório que distingue projetos (este usuário pode se comprometer com este subdir específico). Claro, já temos esse script, pronto para você usar. Como faço para mesclar dois depósitos completamente separados para Se você não se preocupa em manter todo o histórico de um dos repositórios, basta criar um novo diretório em um repositório de projetos e importar o outro. Se você se preocupar em manter o histórico de ambos, então você pode usar svnadmin dump para despejar um repositório e svnadmin load para carregá-lo no outro repositório. Os números de revisão serão apagados, mas você ainda terá o histórico. Peter Davis ltpeterpdavis. cxgt também explica um método usando svns equivalentes aos módulos CVS: desde que a fusão ocorra em árvores de diretório separadas, você pode usar a versão svns dos módulos CVS. Defina a propriedade svn: externals em um diretório para fazer o checkout de diretórios de outros repositórios sempre que o diretório original for desconectado. O repositório permanece separado, mas na cópia de trabalho parece que eles foram mesclados. Se você se comprometer com o diretório importado, isso afetará o repositório externo. A fusão não está completamente limpa: a importação apenas afeta as cópias de trabalho, então você não poderá usar uma URL no primeiro repositório para acessar os módulos importados do segundo. Eles permanecem URLs separados. Há também algumas ferramentas úteis que flutuam na internet, para selecionar e reorganizar as revisões ao combinar vários repositórios. Por exemplo, o script perl svn-merge-repos. pl para operações básicas e as classes Python SvnDumpTool para reorganizações avançadas. Devo armazenar a cópia de trabalho do meu repositório em um servidor NFS para Se você estiver usando um repositório com o back end do Berkeley DB (padrão para repositórios criados com Subversion 1.0 e 1.1, não o padrão a partir de então), recomendamos não armazenar o repositório em um controle remoto Sistema de arquivos (por exemplo, NFS). Embora os bancos de dados e os arquivos de log do Berkeley DB possam ser armazenados em sistemas de arquivos remotos, os arquivos de região compartilhada do Berkeley DB não podem ser armazenados em um sistema de arquivos remoto, de modo que o repositório pode ser acessado com segurança por apenas um único cliente do sistema de arquivos e nem todas as funcionalidades do Subversion estarão disponíveis Até mesmo esse cliente. Se você estiver usando a parte traseira do repositório FSFS, armazenar o repositório em um servidor NFS moderno (ou seja, um que suporte o bloqueio) deve estar bem. As cópias de trabalho podem ser armazenadas no NFS (um cenário comum é quando o diretório inicial está em um servidor NFS). Nos servidores NFS do Linux, devido ao volume de renomeamentos utilizados internamente no Subversion ao verificar arquivos, alguns usuários relataram que a verificação de subárvore deve ser desativada (é habilitada por padrão). Consulte NFS Howto Server Guide e exports (5) para obter mais informações sobre como desabilitar a verificação de subtree. Nós tivemos pelo menos um relatório de cópias de trabalho ficando preso depois de ter sido acessado via SMB. O servidor em questão estava executando uma versão bastante antiga do Samba (2.2.7a). O problema não se repetiu com um Samba mais novo (3.0.6). Como faço para configurar as permissões do repositório corretamente para Tente ter tantos usuários acessarem o repositório quanto possível. Por exemplo, execute o apache ou svnserve - d como um usuário específico e faça o repositório totalmente de propriedade desse usuário. Não permita que outros usuários acessem o repositório via arquivo: urls, e certifique-se de executar svnlook e svnadmin apenas como o usuário que possui o repositório. Se seus clientes estão acessando via arquivo: ou svnssh:. Então não há como evitar o acesso por vários usuários. Nesse caso, leia a última seção no capítulo 6. e preste especial atenção à barra lateral da lista de verificação na parte inferior. Descreve uma série de etapas para tornar este cenário mais seguro. Nota para os usuários SELinux Fedora Core 3 Red Hat Enterprise: Além das permissões regulares do Unix, sob o SELinux, cada arquivo, diretório, processo, etc. tem um contexto de segurança. Quando um processo tenta acessar um arquivo, além de verificar as permissões do Unix, o sistema também verifica se o contexto de segurança do processo é compatível com o contexto de segurança do arquivo. O Fedora Core 3, entre outros sistemas, vem com o SELinux instalado por padrão, configurado para que o Apache seja executado em um contexto de segurança bastante restrito. Para executar o Subversion no Apache, você deve configurar o contexto de segurança do repositório para permitir o acesso do Apache (ou desativar as restrições no Apache, se você acha que tudo isso é excessivo). O comando chcon é usado para definir o contexto de segurança dos arquivos (da mesma forma como o chmod define as permissões Unix tradicionais). Por exemplo, um usuário teve que emitir esse comando para configurar o contexto de segurança para poder acessar o repositório com sucesso. Como faço para remover completamente um arquivo do histórico do repositorys. Existem casos especiais em que você deseja destruir todas as evidências de um arquivo ou confirmar. (Talvez alguém tenha cometido acidentalmente um documento confidencial.) Isso não é tão fácil, porque o Subversion foi projetado deliberadamente para nunca perder informações. As revisões são árvores imutáveis que se construem umas nas outras. A remoção de uma revisão do histórico causaria um efeito de dominó, criando caos em todas as revisões subsequentes e possivelmente invalidando todas as cópias de trabalho. O projeto tem planos, no entanto, algum dia implementar um comando svnadmin obliterado que realizaria a tarefa de excluir permanentemente informações. (Veja o problema 516.) Enquanto isso, seu único recurso é o svnadmin despejar o seu repositório e, em seguida, canalizar o arquivo dump através do svndumpfilter (excluindo o caminho incorreto) em um comando de carga svnadmin. Consulte o capítulo 5 do livro do Subversion para obter detalhes sobre isso. Uma abordagem alternativa é replicar o repositório com svnsync depois de configurar regras de autorização baseadas em caminho que negam o acesso de leitura a todos os caminhos que precisam ser filtrados do histórico. Ao contrário do svndumpfilter. O svnsync traduz automaticamente operações de cópia com um caminho de origem ilegível para adições normais, o que é útil se o histórico envolvendo operações de cópia precisa ser filtrado. Como faço para mudar a mensagem de log para uma revisão depois de ter sido confirmada para As mensagens de log são mantidas no repositório como propriedades anexadas a cada revisão. Por padrão, a propriedade de mensagem de log (svn: log) não pode ser editada uma vez que ela está comprometida. Isso ocorre porque as alterações nas propriedades de revisão (do qual o svn: log é um) fazem com que o valor anterior do propertys seja descartado permanentemente e o Subversion tente impedir que você o faça acidentalmente. No entanto, existem algumas maneiras de obter o Subversion para alterar uma propriedade de revisão. A primeira maneira é que o administrador do repositório habilite as modificações da propriedade de revisão. Isso é feito criando um gancho chamado pré-revprop-change (veja esta seção no livro do Subversion para obter mais detalhes sobre como fazer isso). O gancho pré-revprop-change tem acesso à mensagem de registro anterior antes de ser alterada, para que possa preservá-la de alguma forma (por exemplo, enviando um e-mail). Uma vez que as modificações da propriedade de revisão estão ativadas, você pode alterar uma mensagem de log de revisões passando a opção --revprop para svn propedit ou svn propset. Como qualquer um destes: onde N é o número de revisão cuja mensagem de log deseja alterar e URL é a localização do repositório. Se você executar este comando a partir de uma cópia de trabalho, você pode deixar o URL. A segunda maneira de alterar uma mensagem de log é usar o setlog svnadmin. Isso deve ser feito consultando a localização do repositorys no sistema de arquivos. Você não pode modificar um repositório remoto usando este comando. Onde REPOSPATH é o local do repositório, N é o número de revisão cuja mensagem de log deseja alterar e FILE é um arquivo contendo a nova mensagem de logs. Se o gancho pré-revprop-change não estiver no lugar (ou você quiser ignorar o script hook por algum motivo), você também pode usar a opção --bypass-hooks. No entanto, se você decidir usar esta opção, tenha muito cuidado. Você pode ignorar coisas como notificações por e-mail da mudança ou sistemas de backup que acompanham as propriedades de revisão. Como faço para enviar um patch para o Subversion para Uma vez que você tenha digerido isso, envie um e-mail para a lista dev com a palavra PATCH e uma descrição de linha única no assunto e inclua o patch inline em seu e-mail (a menos que o MUA o munge totalmente). Em seguida, um comitê irá buscá-lo, aplicá-lo (fazer as mudanças de formatação ou de conteúdo necessárias) e verificá-lo. O processo básico parece assim: claro, o e-mail que você envia deve conter uma longa e longa explicação sobre o que o patch faz , De acordo com o Guia da Comunidade do Subversion. Mas você já sabe disso, desde que você leu e entendeu completamente antes de realmente piratear o código, certo. ) À procura de algo a fazer Dê uma olhada na nossa página de ideias. Como posso fazer uma importação no local (ou seja, adicionar uma árvore ao Subversion de modo que os dados originais se tornem uma cópia de trabalho diretamente) para Suponha, por exemplo, que você quisesse colocar alguns etc. sob controle de versão dentro do seu repositório: isso leva Vantagem de uma característica não-imediatamente óbvia do svn checkout. Você pode verificar um diretório do repositório diretamente em um diretório existente. Aqui, primeiro criamos um novo diretório vazio no repositório e, em seguida, verifique isso em etc. Transformando etc em uma cópia de trabalho. Uma vez que é feito, você pode usar comandos svn add simples para selecionar arquivos e subárvores para adicionar ao repositório. Se o conteúdo completo do diretório deve ser importado, em vez de um subconjunto de conteúdo, essa seqüência mais curta de comandos pode ser usada para executar a importação e, em seguida, transformar o diretório em uma cópia de trabalho Subversion: há um problema arquivado para melhorar a importação do svn Para poder converter a árvore importada em uma cópia de trabalho, veja automaticamente o problema 1328. O que é esse ciclo de dumpload às quais as pessoas falam ao atualizar um servidor Subversion para o esquema do banco de dados do repositório Subversions mudou ocasionalmente durante o desenvolvimento. Os repositórios antigos, criados com uma versão de desenvolvimento pré-1.0 do Subversion, podem exigir a seguinte operação ao atualizar. Se ocorrer uma mudança de esquema entre as versões X e Y do Subversion, os administradores do repositório atualizando para Y devem fazer o seguinte: Desligue o svnserve, Apache e qualquer outra coisa que possa estar acessando o repositório. Svnadmin dump pathtorepository dumpfile. txt. Usando a versão X do svnadmin. Mv pathtorepository pathtoesaved-old-repository Agora atualize para Subversion Y (ou seja, crie e instale Y, substituindo X). Svnadmin create pathtorepository. Usando a versão Y do svnadmin. Svnadmin load pathtorepository lt dumpfile. txt. Novamente usando a versão Y do svnadmin. Copie sobre scripts de gancho, etc., do repositório antigo para o novo. Reinicie svnserve, Apache, etc. Consulte esta seção do livro do Subversion para obter mais detalhes sobre o despejo e o carregamento. Nota . A maioria das atualizações do Subversion não envolve um despejo e carga. Quando é necessário, o anúncio de lançamento eo arquivo CHANGES para a nova versão ostentarão avisos proeminentes sobre isso. Se você não perceber tal aviso, então não houve mudança de esquema, e não é necessário nenhum Dumpload. Como faço para permitir que os clientes se autentiquem contra um controlador de domínio do Windows usando autenticação SSPI para TortoiseSVN tem um excelente documento que descreve a configuração de um servidor Subversion no Windows. Vá para tortoisesvndocsreleaseTortoiseSVNentsvn-serversetup. htmltsvn-serversetup-apache-5. Para ver a seção sobre autenticação SSPI. Uma parte importante da configuração é a linha: sem essa linha, os navegadores que oferecem suporte a SSPI solicitarão as credenciais dos usuários, mas os clientes que não suportam SSPI, como o Subversion, não solicitarão. (The current release of Neon - Subversions HTTP library - handles only basic authentication.) Because the client never asks for credentials, any action that requires authentication will fail. Adding this line tells modauthsspi to use basic authentication with the client, but to use the Windows domain controller to authenticate the credentials. I dont like the. svn directory name, and prefer SVN or something else. How do I change it para We recommend that you live with. svn if you possibly can. However, if you are using Visual Studio 2002 or 2003 under Windows, you might need to set the environment variable SVNASPDOTNETHACK, as described here . Or you could use a completely custom name for the administrative directory. We recommend against this, because your working copy would probably not work with Subversion clients other than the one you customized. However, if you absolutely must do this, just change this line in subversionincludesvnwc. h from then recompile your client. How do I change the case of a filename para This problem comes up in two situations. If youre adding files on an operating system with a case-insensitive filesystem, such as Windows, you might find you accidentally add a file with the wrong case in the filename. Alternatively, you may just decide to change the case of an existing file in the repository. If youre working in a case-sensitive file system, this is no problem at all. Just move the file to the new name, e. g., From Subversion 1.7 onwards, this also works on Windows, even though its using a case-insensitive filesystem. If you are using Subversion 1.6 or older on Windows, or if youre using a case-insensitive filesystem with an operating system other than Windows, this technique wont work. In this case, you can accomplish this by copying the file somewhere temporary, deleting the file from Subversion, then adding the copy with the correct case. Or a better way is to perform a move operation with Subversion URLs. Using URLs is recommended, because it will preserve history for the file, and will take effect immediately. Both ways will leave Windows working copies with problems, however, because Windows can still get confused when trying to update the conflicting filenames. (Youll get a message like svn: Failed to add file File. java: object of the same name already exists ). One way of fixing the problem is to delete your working copy and check out again. If you do not want to do this, you must perform a two step update. For each file with the wrong case, the following command will change the case: To update the working copy, change to the relevant directory and do: The first update will remove file. java from your working copy, the second update will add File. java . leaving you with a correct working copy. Or if you had a lot of problematic files, you can update the working copy this way: As you can see, adding a file with the wrong case is tricky to fix on an operating system that has a case insensitive filesystem. Do try to get it right when you add the file the first time To prevent the problem from occurring in the first place, you can create a pre-commit hook that calls the file check-case-insensitive. pl . That file lives in the Subversion source tarball, in the directory contribhook-scripts . I cant use tags to merge changes from a branch into the trunk like I used to with CVS, can I para As shown below it is possible to merge from a branch to the trunk without remembering one revision number. Or vice versa (not shown in the example). The example below presumes an existing repository in homerepos in which you want to start a branch named bar containing a file named foo you are going to edit. For the purpose of tracing branch merges, this repository has set up tagsbranchtraces to keep tags. Why doesnt the Revision keyword do what I want It expands to the files last-changed revision, but I want something that will expand to the files current revision. para Subversion increments the revision number of the repository as a whole, so it cant expand any keyword to be that number - it would have to search and possibly modify every file in your working copy on every update and commit. The information you want (the revision of your working copy) is available from the command svnversion it gives you information on the revision level of a working copy given a path (see svnversion --help for details). You can incorporate it into your build or release process to get the information you need into the source itself. For example, in a build environment based on GNU make . add something like this to your Makefile . (Note that this will not work on non-GNU versions of make . Dont use it if your build process needs to be portable.) Or try this recipe: Windows users may want to use SubWCRev. exe . available from the TortoiseSVN download page it replaces all WCREV tags in a given file with the current working copy revision. Another alternative is creating a wrapper for svn commit, which does some automatic replacement in files before commit (be careful not to mess things up though -- silent manipulation of files right before commit can be scary for a user). That way you can inject any metadata you want (and it will be committed with the regular content of the file into the repository). Does Subversion have a keyword which behaves like Log in CVS para No. There is no equivalent for the Log keyword in CVS. If you want to retrieve a log for a specific file, you can run svn log your-file-name or svn log url-to-your-file. From the mailing list some explanations why Log is bad: I dont care about that. I want to use it anyway. Will you implement it No. There are no plans to implement it ourselves or accept patches which implement this feature. If you want to distribute your files with some kind of changelog included, you might be able to work around this limitation in your build system. I have a file in my project that every developer must change, but I dont want those local mods to ever be committed. How can I make svn commit ignore the file para The answer is: dont put that file under version control. Instead, put a template of the file under version control, something like file. tmpl. Then, after the initial svn checkout, have your users (or your build system) do a normal OS copy of the template to the proper filename, and have users customize the copy. The file is unversioned, so it will never be committed. And if you wish, you can add the file to its parent directorys svn:ignore property, so it doesnt show up as in the svn status command. When I access a repository using svnssh, my password is not cached in. subversionauth. How do I avoid having to type it so often para ssh has its own passphrases and its own authentication-caching scheme. Its auth caching is external to Subversion, and must be set up independently of Subversion. OpenSSH includes ssh-keygen to create the keys, ssh-agent to cache passphrases, and ssh-add to add passphrases to the agents cache. A popular script to simplify usage of ssh-agent is keychain . On Windows, PuTTY is a popular alternative ssh client see PuTTYgen to import OpenSSH keys and pageant to cache passphrases. Setting up ssh-agent is outside the scope of this document, but a Google search for ssh-agent will quickly get you answers. Or if youre really impatient, try one of these: My svnserve binary is in a directory that isnt on my users default PATH s, they use svnssh, and I cant figure out how to modify their PATH so that they can run svnserve . para Note: this all assumes youre using OpenSSH. There are other ssh implementations out there, and presumably they will allow you to do something similar, but we dont yet know the details. Youve tried fiddling with their various login files, like. bashprofile . and nothing works Thats because ssh ignores those files when the Subversion client invokes it. But theres no need to modify PATH instead, you can directly give ssh the full name of the svnserve command. Heres how to do it: For each user who needs svnssh access, generate a new ssh public-key pair which they will use only for Subversionmdashnot for logging in normally. Have them give the keypair a distinctive name, like. sshiddsa. subversion . Add the public part of the key to their. sshauthorizedkeys file on the server machine, after first inserting a bit of magic at the beginning of the line before the word ssh-rsa or ssh-dss . like this: Deprecated FAQ Why is my repository taking up so much disk space para The repository stores all your data in a Berkeley DB environment in the reposdb subdirectory. The environment contains a collection of tables and bunch of logfiles (log.). Berkeley DB journals all changes made to the tables, so that the tables can be recovered to a consistent state in case of interruptions (more info ). The logfiles will grow forever, eating up disk space, unless you, (as the repository administrator) do something about it. At any given moment, Berkeley DB is only using a few logfiles actively (see this post and its associated thread) the rest can be safely deleted. If you keep all the logfiles around forever, then in theory Berkeley DB can replay every change to your repository from the day it was born. But in practice, if youre making backups, its probably not worth the cost in disk space. Use svnadmin to see which log files can be deleted. You may want a cron job to do this. You could instead use Berkeley DBs dbarchive command: See also svnadmin hotcopy or hotbackup. py . Note: If you use Berkeley DB 4.2, Subversion will create new repositories with automatic log file removal enabled. You can change this by passing the --bdb-log-keep option to svnadmin create. Refer to the section about the DBLOGAUTOREMOVE flag in the Berkeley DB manual. My repository seems to get stuck all the time, giving me errors about needing recovery (DBRUNRECOVERY). What could be the cause para The Berkeley DB database in your repository is sensitive to interruptions. If a process accessing the database exits without cleanly closing the environment, then the database is left in an inconsistent state. Common causes of this include: the process exiting when it hits a permission problem the process crashingsegfaulting the process being forcibly killed running out of disk space For most of these cases, you should run svnadmin recover, which rewinds the repository back to a consistent state see this question for details. Note that running out of disk space, combined with frequent checkouts or updates, can cause the repository to crash in a way where recovery is not possible (so keep backups). Segfaults, forced killings, and running out of disk space are pretty rare. Permission problems are far more common: one process accesses the repository and accidentally changes ownership or permissions, then another process tries to access and chokes on the permissions. The best way to prevent this is to get your repository permissions and ownership set up correctly. See here for our recommendations. Every time I try to access my repository, the process just hangs. Is my repository corrupt para Your repository is not corrupt, nor is your data lost. If your process accesses the repository directly (moddavsvn, svnlook, svnadmin, or if you access a file: URL), then its using Berkeley DB to access your data. Berkeley DB is a journaling system, meaning that it logs everything it is about to do before it does so. If your process is interrupted (Control-C, or segfault), then a lockfile is left behind, along with a logfile describing unfinished business. Any other process that attempts to access the database will just hang, waiting for the lockfile to disappear. To awaken your repository, you need to ask Berkeley DB to either finish the work, or rewind the database to a previous state that is known to be consistent. WARNING: you can seriously corrupt your repository if you run recover and another process accesses the repository. Make absolutely sure you disable all access to the repository before doing this (by shutting down Apache, removing executable permissions from svn). Make sure you run this command as the user that owns and manages the database, and not as root, else it will leave root-owned files in the db directory which cannot be opened by the non-root user that manages the database, which is typically either you or your Apache process. Also be sure to have the correct umask set when you run recover, since failing to do so will lock out users that are in the group allowed to access the repository. Once the command has completed, check the permissions in the db directory of the repository. Sometimes svnadmin recover doesnt work. You may see it give errors like this: In that case, try Berkeley DBs native dbrecover utility (see dbrecover documentation ). It usually lives in a bin subdirectory of the Berkeley DB installation, for example if you installed Berkeley DB from source, it might be usrlocalBerkeleyDB.4.2bindbrecover or on systems where Berkeley DB comes prepackaged it might just be usrbindbrecover . If you have multiple versions of Berkeley DB installed, make sure that the version of dbrecover you use matches the version of Berkeley DB with which your repository was created. Run dbrecover with the - c (catastrophic recovery) flag. You can also add - v for verbosity, and - h with an argument telling it what db environment to recover (so you dont have to cd into that directory). Thus: Run this command as the same user that owns the repository, and again, make absolutely sure that no other processes are accessing the repository while you do this (e. g. shut down svnserve or Apache). My repository keeps giving errors saying Cannot allocate memory. What should I do para If youre using access, Cannot allocate memory errors show up in the httpd error log and look something like this: It usually means that a Berkeley DB repository has run out of database locks (this does not happen with FSFS repositories). It shouldnt happen in the course of normal operations, but if it does, the solution is to run database recovery as described here. If it happens often, you probably need to raise the default lock parameters ( setlkmaxlocks . setlkmaxlockers . and setlkmaxobjects ) in the dbDBCONFIG file. When changing DBCONFIG in an existing repository, remember to run recovery afterwards. When I start Apache, moddavsvn complains about a bad database version, that it found db-3.X, rather than db-4.X. para Your apr-util linked against DB-3, and svn linked against DB-4. Unfortunately, the DB symbols arent different. When moddavsvn is loaded into Apaches process-space, it ends up resolving the symbol names against apr-utils DB-3 library. The solution is to make sure apr-util compiles against DB-4. You can do this by passing specific switches to either apr-utils or apaches configure: --with-dbmdb4 --with-berkeley-dbthedbprefix. Im getting Function not implemented errors on Red Hat 9, and nothing works. How do I fix this para This is not really a problem with Subversion, but it often affects Subversion users. Red Hat 9 and Fedora ship with a Berkeley DB library that relies on the kernel support for NPTL (the Native Posix Threads Library). The kernels that Red Hat provides have this support built in, but if you compile your own kernel, then you may well not have the NPTL support. If that is the case, then you will see errors like this: This can be fixed in one of several ways: Rebuild Berkeley DB for the kernel youre using. Use a Red Hat 9 kernel. Apply the NPTL patches to the kernel youre using. Use a recent (2.5.x) kernel with the NPTL support included. Check if environment variable LDASSUMEKERNEL is set to 2.2.5. and if so, unset it before starting Subversion (Apache). (You usually would set this variable to run Wine or Winex on Red Hat 9) To use the NPTL version of Berkeley DB you also need to use a glibc library with NPTL support, which probably means the i686 version. See svn. haxx. seusersarchive-2004-030488.shtml for details. Im getting the error svn: bdb: call implies an access method which is inconsistent with previous calls. How do I fix this para Berkeley DB 4.1 has shown itself to be rather unstable - both 4.0 and 4.2 are better. This error message is a symptom of one unique way in which 4.1 will sometimes break. The problem is that the database format field for one of the tables that make up a Subversion repository using the Berkeley DB backend has become corrupted. For unknown reasons, this is almost always the copies table, which switches from the btree type to the recno type. Simple recovery procedures are outlined below - if they do not succeed, you should contact the Subversion Users mailing list . Ensure that no other processes will attempt to access your repository. Now, back up your repository to a tar or zip file or similar. Change to the db subdirectory of your repository. rm db. log. dbdump - p - r copies gt copies. dump Now edit copies. dump . In the section near the top, change typerecno to typebtree , and delete the line beginning relen . rm copies dbload copies lt copies. dump svnadmin dump. Gt. ..my-recovered. svndump Now create a new repository, reload the dump file just produced, and copy across any custom hooks or configuration. Verify that the highest revision number in the new repository is what you think it should be. After upgrading to Berkeley DB 4.3 or later, Im seeing repository errors. para Prior to Berkeley DB 4.3, svnadmin recover worked to upgrade a Berkeley DB repository in-place. However, due to a change in the behaviour of Berkeley DB in version 4.3, this now fails. Use this procedure to upgrade your repository in-place to Berkeley DB 4.3 or later: Make sure no process is accessing the repository (stop Apache, svnserve, restrict access via file:, svnlook, svnadmin, etc.) Using an older svnadmin binary (that is, linked to an older Berkeley DB): Recover the repository: svnadmin recover pathtorepository Make a backup of the repository. Delete all unused log files. You can see them by running svnadmin list-unused-dblogs pathtorepeository Delete the shared-memory files. These are files in the repositorys db directory, of the form db.00 The repository is now usable by Berkeley DB 4.3. Why do read-only operations still need repository write access para Certain client operations are read-only, like checkouts and updates. From an access-control standpoint, Apache treats them as such. But libsvnfs (the repository filesystem API) still has to write temporary data in order to produce tree-deltas. So the process accessing the repository always requires both read and write access to the Berkeley DB files in order to function. In particular, the repository responds to many read-only operations by comparing two trees. One tree is the usually the HEAD revision, and the other is often a temporary transaction-tree -- thus the need for write access. This limitation only applies to the Berkeley DB backend the FSFS backend does not exhibit this behaviour. Binary Files and Translation In the most general sense, Subversion handles binary files more gracefully than CVS does. Because CVS uses RCS, it can only store successive full copies of a changing binary file. Subversion, however, expresses differences between files using a binary differencing algorithm, regardless of whether they contain textual or binary data. That means all files are stored differentially (compressed) in the repository. CVS users have to mark binary files with - kb flags to prevent data from being garbled (due to keyword expansion and line-ending translations). They sometimes forget to do this. Subversion takes the more paranoid route. First, it never performs any kind of keyword or line-ending translation unless you explicitly ask it to do so (see the section called Keyword Substitution and the section called End-of-Line Character Sequences for more details). By default, Subversion treats all file data as literal byte strings, and files are always stored in the repository in an untranslated state. Second, Subversion maintains an internal notion of whether a file is text or binary data, but this notion is only extant in the working copy. During an svn update . Subversion will perform contextual merges on locally modified text files, but will not attempt to do so for binary files. To determine whether a contextual merge is possible, Subversion examines the svn:mime-type property. If the file has no svn:mime-type property, or has a MIME type that is textual (e. g. text ), Subversion assumes it is text. Otherwise, Subversion assumes the file is binary. Subversion also helps users by running a binary-detection algorithm in the svn import and svn add commands. These commands will make a good guess and then (possibly) set a binary svn:mime-type property on the file being added. (If Subversion guesses wrong, the user can always remove or hand-edit the property.) You are reading Version Control with Subversion (for Subversion 1.7), by Ben Collins-Sussman, Brian W. Fitzpatrick, and C. Michael Pilato. This work is licensed under the Creative Commons Attribution License v2.0 . To view a copy of this license, visit Creative Commons site or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA. To submit comments, corrections, or other contributions to the text, please visit svnbook. Properties Weve already covered in detail how Subversion stores and retrieves various versions of files and directories in its repository. Whole chapters have been devoted to this most fundamental piece of functionality provided by the tool. And if the versioning support stopped there, Subversion would still be complete from a version control perspective. Mas não pára por aí. In addition to versioning your directories and files, Subversion provides interfaces for adding, modifying, and removing versioned metadata on each of your versioned directories and files. We refer to this metadata as properties . and they can be thought of as two-column tables that map property names to arbitrary values attached to each item in your working copy. Generally speaking, the names and values of the properties can be whatever you want them to be, with the constraint that the names must contain only ASCII characters. And the best part about these properties is that they, too, are versioned, just like the textual contents of your files. You can modify, commit, and revert property changes as easily as you can file content changes. And the sending and receiving of property changes occurs as part of your typical commit and update operationsyou dont have to change your basic processes to accommodate them. Subversion has reserved the set of properties whose names begin with svn: as its own. While there are only a handful of such properties in use today, you should avoid creating custom properties for your own needs whose names begin with this prefix. Otherwise, you run the risk that a future release of Subversion will grow support for a feature or behavior driven by a property of the same name but with perhaps an entirely different interpretation. Properties show up elsewhere in Subversion, too. Just as files and directories may have arbitrary property names and values attached to them, each revision as a whole may have arbitrary properties attached to it. The same constraints applyhuman-readable names and anything-you-want binary values. The main difference is that revision properties are not versioned. In other words, if you change the value of, or delete, a revision property, theres no way, within the scope of Subversions functionality, to recover the previous value. Subversion has no particular policy regarding the use of properties. It asks only that you do not use property names that begin with the prefix svn: as thats the namespace that it sets aside for its own use. And Subversion does, in fact, use propertiesboth the versioned and unversioned variety. Certain versioned properties have special meaning or effects when found on files and directories, or they house a particular bit of information about the revisions on which they are found. Certain revision properties are automatically attached to revisions by Subversions commit process, and they carry information about the revision. Most of these properties are mentioned elsewhere in this or other chapters as part of the more general topics to which they are related. For an exhaustive list of Subversions predefined properties, see the section called Subversion Properties in Chapter 9, Subversion Complete Reference . While Subversion automatically attaches properties ( svn:date. svn:author. svn:log. and so on) to revisions, it does not presume thereafter the existence of those properties, and neither should you or the tools you use to interact with your repository. Revision properties can be deleted programmatically or via the client (if allowed by the repository hooks) without damaging Subversions ability to function. So, when writing scripts which operate on your Subversion repository data, do not make the mistake of assuming that any particular revision property exists on a revision. In this section, we will examine the utilityboth to users of Subversion and to Subversion itselfof property support. Youll learn about the property-related svn subcommands and how property modifications affect your normal Subversion workflow. Why Properties Just as Subversion uses properties to store extra information about the files, directories, and revisions that it contains, you might also find properties to be of similar use. You might find it useful to have a place close to your versioned data to hang custom metadata about that data. Say you wish to design a web site that houses many digital photos and displays them with captions and a datestamp. Now, your set of photos is constantly changing, so youd like to have as much of this site automated as possible. These photos can be quite large, so as is common with sites of this nature, you want to provide smaller thumbnail images to your site visitors. Now, you can get this functionality using traditional files. That is, you can have your image123.jpg and an image123-thumbnail. jpg side by side in a directory. Or if you want to keep the filenames the same, you might have your thumbnails in a different directory, such as thumbnailsimage123.jpg. You can also store your captions and datestamps in a similar fashion, again separated from the original image file. But the problem here is that your collection of files multiplies with each new photo added to the site. Now consider the same web site deployed in a way that makes use of Subversions file properties. Imagine having a single image file, image123.jpg. with properties set on that file that are named caption. datestamp. and even thumbnail. Now your working copy directory looks much more manageablein fact, it looks to the casual browser like there are nothing but image files in it. But your automation scripts know better. They know that they can use svn (or better yet, they can use the Subversion language bindingssee the section called Using the APIs ) to dig out the extra information that your site needs to display without having to read an index file or play path manipulation games. While Subversion places few restrictions on the names and values you use for properties, it has not been designed to optimally carry large property values or large sets of properties on a given file or directory. Subversion commonly holds all the property names and values associated with a single item in memory at the same time, which can cause detrimental performance or failed operations when extremely large property sets are used. Custom revision properties are also frequently used. One common such use is a property whose value contains an issue tracker ID with which the revision is associated, perhaps because the change made in that revision fixes a bug filed in the tracker issue with that ID. Other uses include hanging more friendly names on the revisionit might be hard to remember that revision 1935 was a fully tested revision. But if theres, say, a test-results property on that revision with the value all passing. thats meaningful information to have. And Subversion allows you to easily do this via the --with-revprop option of the svn commit command: Searchability (or, Why Not Properties) For all their utility, Subversion propertiesor, more accurately, the available interfaces to themhave a major shortcoming: while it is a simple matter to set a custom property, finding that property later is a whole different ball of wax. Trying to locate a custom revision property generally involves performing a linear walk across all the revisions of the repository, asking of each revision, Do you have the property Im looking for Use the --with-all-revprops option with the svn log commands XML output mode to facilitate this search. Notice the presence of the custom revision property testresults in the following output: Trying to find a custom versioned property is painful, too, and often involves a recursive svn propget across an entire working copy. In your situation, that might not be as bad as a linear walk across all revisions. But it certainly leaves much to be desired in terms of both performance and likelihood of success, especially if the scope of your search would require a working copy from the root of your repository. For this reason, you might chooseespecially in the revision property use caseto simply add your metadata to the revisions log message using some policy-driven (and perhaps programmatically enforced) formatting that is designed to be quickly parsed from the output of svn log . It is quite common to see the following in Subversion log messages: But here again lies some misfortune. Subversion doesnt yet provide a log message templating mechanism, which would go a long way toward helping users be consistent with the formatting of their log-embedded revision metadata. Manipulating Properties The svn program affords a few ways to add or modify file and directory properties. For properties with short, human-readable values, perhaps the simplest way to add a new property is to specify the property name and value on the command line of the svn propset subcommand: But weve been touting the flexibility that Subversion offers for your property values. And if you are planning to have a multiline textual, or even binary, property value, you probably do not want to supply that value on the command line. So the svn propset subcommand takes a --file ( - F ) option for specifying the name of a file that contains the new property value. There are some restrictions on the names you can use for properties. A property name must start with a letter, a colon (. ), or an underscore ( ) after that, you can also use digits, hyphens ( - ), and periods (. ). 13 In addition to the propset command, the svn program supplies the propedit command. This command uses the configured editor program (see the section called Config ) to add or modify properties. When you run the command, svn invokes your editor program on a temporary file that contains the current value of the property (or that is empty, if you are adding a new property). Then, you just modify that value in your editor program until it represents the new value you wish to store for the property, save the temporary file, and then exit the editor program. If Subversion detects that youve actually changed the existing value of the property, it will accept that as the new property value. If you exit your editor without making any changes, no property modification will occur: We should note that, as with other svn subcommands, those related to properties can act on multiple paths at once. This enables you to modify properties on whole sets of files with a single command. For example, we could have done the following: All of this property adding and editing isnt really very useful if you cant easily get the stored property value. So the svn program supplies two subcommands for displaying the names and values of properties stored on files and directories. The svn proplist command will list the names of properties that exist on a path. Once you know the names of the properties on the node, you can request their values individually using svn propget . This command will, given a property name and a path (or set of paths), print the value of the property to the standard output stream. Theres even a variation of the proplist command that will list both the name and the value for all of the properties. Simply supply the --verbose ( - v ) option. The last property-related subcommand is propdel . Since Subversion allows you to store properties with empty values, you cant remove a property altogether using svn propedit or svn propset . For example, this command will not yield the desired effect: You need to use the propdel subcommand to delete properties altogether. The syntax is similar to the other property commands: Remember those unversioned revision properties You can modify those, too, using the same svn subcommands that we just described. Simply add the --revprop command-line parameter and specify the revision whose property you wish to modify. Since revisions are global, you dont need to specify a target path to these property-related commands so long as you are positioned in a working copy of the repository whose revision property you wish to modify. Otherwise, you can simply provide the URL of any path in the repository of interest (including the repositorys root URL). For example, you might want to replace the commit log message of an existing revision. 14 If your current working directory is part of a working copy of your repository, you can simply run the svn propset command with no target path: But even if you havent checked out a working copy from that repository, you can still effect the property change by providing the repositorys root URL: Note that the ability to modify these unversioned properties must be explicitly added by the repository administrator (see the section called Commit Log Message Correction ). Thats because the properties arent versioned, so you run the risk of losing information if you arent careful with your edits. The repository administrator can set up methods to protect against this loss, and by default, modification of unversioned properties is disabled. Users should, where possible, use svn propedit instead of svn propset . While the end result of the commands is identical, the former will allow them to see the current value of the property that they are about to change, which helps them to verify that they are, in fact, making the change they think they are making. This is especially true when modifying unversioned revision properties. Also, it is significantly easier to modify multiline property values in a text editor than at the command line. Properties and the Subversion Workflow Now that you are familiar with all of the property-related svn subcommands, lets see how property modifications affect the usual Subversion workflow. As we mentioned earlier, file and directory properties are versioned, just like your file contents. As a result, Subversion provides the same opportunities for mergingcleanly or with conflictssomeone elses modifications into your own. As with file contents, your property changes are local modifications, made permanent only when you commit them to the repository with svn commit . Your property changes can be easily unmade, toothe svn revert command will restore your files and directories to their unedited statescontents, properties, and all. Also, you can receive interesting information about the state of your file and directory properties by using the svn status and svn diff commands. Notice how the status subcommand displays M in the second column instead of the first. That is because we have modified the properties on calcbutton. c. but not its textual contents. Had we changed both, we would have seen M in the first column, too. (We cover svn status in the section called See an overview of your changes ). As with file contents, local property modifications can conflict with changes committed by someone else. If you update your working copy directory and receive property changes on a versioned object that clash with your own, Subversion will report that the object is in a conflicted state. Subversion will also create, in the same directory as the conflicted object, a file with a. prej extension that contains the details of the conflict. You should examine the contents of this file so you can decide how to resolve the conflict. Until the conflict is resolved, you will see a C in the second column of svn status output for that object, and attempts to commit your local modifications will fail. To resolve property conflicts, simply ensure that the conflicting properties contain the values that they should, and then use the svn resolve --acceptworking command to alert Subversion that you have manually resolved the problem. You might also have noticed the nonstandard way that Subversion currently displays property differences. You can still use svn diff and redirect its output to create a usable patch file. The patch program will ignore property patchesas a rule, it ignores any noise it cant understand. This does, unfortunately, mean that to fully apply a patch generated by svn diff using patch . any property modifications will need to be applied by hand. Subversion 1.7 improves this situation in two ways. First, its nonstandard display of property differences is at least machine-readablean improvement over the display of properties in versions prior to 1.7. But Subversion 1.7 also introduces the svn patch subcommand, designed specifically to handle the additional information which svn diff s output can carry, applying those changes to the Subversion working copy. Of specific relevance to our topic, property differences present in patch files generated by svn diff in Subversion 1.7 or better can be automatically applied to a working copy by the svn patch command. For more about svn patch . see svn patch in Chapter 9, Subversion Complete Reference . Theres one exception to how property changes are reported by svn diff . changes to Subversions special svn:mergeinfo propertyused to track information about merges which have been performed in your repositoryare described in a more human-readable fashion. This is quite helpful to the humans who have to read those descriptions. But it also serves to cause patching programs (including svn patch ) to skip those change descriptions as noise. This might sound like a bug, but it really isnt because this property is intended to be managed solely by the svn merge subcommand. For more about merge tracking, see Chapter 4, Branching and Merging . Automatic Property Setting Properties are a powerful feature of Subversion, acting as key components of many Subversion features discussed elsewhere in this and other chapterstextual diff and merge support, keyword substitution, newline translation, and so on. But to get the full benefit of properties, they must be set on the right files and directories. Unfortunately, that step can be easily forgotten in the routine of things, especially since failing to set a property doesnt usually result in an obvious error (at least compared to, say, failing to add a file to version control). To help your properties get applied to the places that need them, Subversion provides a couple of simple but useful features. Whenever you introduce a file to version control using the svn add or svn import commands, Subversion tries to assist by setting some common file properties automatically. First, on operating systems whose filesystems support an execute permission bit, Subversion will automatically set the svn:executable property on newly added or imported files whose execute bit is enabled. (See the section called File Executability later in this chapter for more about this property.) Second, Subversion tries to determine the files MIME type. If youve configured a mime-types-files runtime configuration parameter, Subversion will try to find a MIME type mapping in that file for your files extension. If it finds such a mapping, it will set your files svn:mime-type property to the MIME type it found. If no mapping file is configured, or no mapping for your files extension could be found, Subversion will fall back to heuristic algorithms to determine the files MIME type. Depending on how it is built, Subversion 1.7 can make use of file scanning libraries 15 to detect a files type based on its content. Failing all else, Subversion will employ its own very basic heuristic to determine whether the file contains nontextual content. If so, it automatically sets the svn:mime-type property on that file to applicationoctet-stream (the generic this is a collection of bytes MIME type). Of course, if Subversion guesses incorrectly, or if you wish to set the svn:mime-type property to something more preciseperhaps imagepng or applicationx-shockwave-flash you can always remove or edit that property. (For more on Subversions use of MIME types, see the section called File Content Type later in this chapter.) UTF-16 is commonly used to encode files whose semantic content is textual in nature, but the encoding itself makes heavy use of bytes which are outside the typical ASCII character byte range. As such, Subversion will tend to classify such files as binary files, much to the chagrin of users who desire line-based differencing and merging, keyword substitution, and other behaviors for those files. Subversion also provides, via its runtime configuration system (see the section called Runtime Configuration Area ), a more flexible automatic property setting feature that allows you to create mappings of filename patterns to property names and values. Once again, these mappings affect adds and imports, and can not only override the default MIME type decision made by Subversion during those operations, but can also set additional Subversion or custom properties, too. For example, you might create a mapping that says that anytime you add JPEG filesones whose names match the pattern. jpg Subversion should automatically set the svn:mime-type property on those files to imagejpeg. Or perhaps any files that match. cpp should have svn:eol-style set to native. and svn:keywords set to Id. Automatic property support is perhaps the handiest property-related tool in the Subversion toolbox. See the section called Config for more about configuring that support. Subversion administrators commonly ask if it is possible to configure, on the server side, a set of property definitions which all connecting clients will automatically consider when operating on working copies checked out from that server. Unfortunately, Subversion doesnt offer this feature. Administrators can use hook scripts to validate that the properties added to and modified on files and directories match the administrators preferred policies, rejecting commits which are non-compliant in this fashion. (See the section called Implementing Repository Hooks for more about hook scripts.) But theres no way to automatically dictate those preferences to Subversion clients beforehand. 13 If youre familiar with XML, this is pretty much the ASCII subset of the syntax for XML Name . 14 Fixing spelling errors, grammatical gotchas, and just-plain-wrongness in commit log messages is perhaps the most common use case for the --revprop option. 15 Currently, libmagic is the support library used to accomplish this.
Comments
Post a Comment